JDBC中Preparedstatement的简单使用

首先要有一个Connection,下面上代码

PreparedStatement stmt = null;
ResultSet rs = null;
try {
	stmt = con.prepareStatement(sql);
	stmt.setString(1, sth); //可以用这个方法智能替换sql里的问号
	rs = stmt.executeQuery();
	while (rs.next()) {
		//该干嘛干嘛
	}
} catch (SQLException ex) {
} finally {
	if(rs != null) {
		try{ rs.close(); } catch(Exception e) {}
	}
	if(stmt != null) {
		try{ stmt.close(); } catch(Exception e) {}
	}
	connection.close();
}

另外这货执行插入语句的话还有返回id的功能

执行stmt的那一块换成

stmt.registerReturnParameter(11, Types.BIGINT);
stmt.executeUpdate();
rs = stmt.getReturnResultSet();

然后rs.getInt(1)能获得id



你可能感兴趣的:(JDBC中Preparedstatement的简单使用)