Java中的PreparedStatement接口继承自Statement,但与Statement有两点不同:
PreparedStatement 实例包含已编译的 SQL 语句。这就是使语句“准备好”。包含于 PreparedStatement 对象中的 SQL 语句可具有一个或多个 IN 参数。IN参数的值在 SQL 语句创建时未被指定。相反的,该语句为每个 IN 参数保留一个问号(“?”)作为占位符。每个问号的值必须在该语句执行之前,通过适当的setXXX 方法来提供。
作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能。另外它还添加了一整套方法,用于设置发送给数据库以取代 IN 参数占位符的值。同时,三种方法 execute、 executeQuery 和 executeUpdate 已被更改以使之不再需要参数。这些方法的 Statement 形式(接受 SQL 语句参数的形式)不应该用于 PreparedStatement 对象。
public interface PreparedStatement extends Statement
In the following example of setting a parameter, con
represents an active connection:
PreparedStatement pstmt = con.prepareStatement("update employees set salary = ? where id = ?"); ---a
pstmt.setBigDecimal(1,88888); --b
pstmt.setInt(2,11209); --c
pstmt.execute(); --d
con.commit(); --e
a语句:创建了包含带两个IN参数占位符的SQL语句的PreparedStatement对象。
b&c语句:调用setXXX方法设置每个占位符“?”的值。setXXX方法的第一个参数是要设置的参数的序数位置。eg:salary=88888,id=11209。
d语句:执行b&c语句。
e语句:提交给DB。
知识点:
setXXX 方法中的 XXX 是 Java 类型。它是一种隐含的 JDBC 类型(一般 SQL 类型),因为驱动程序将把 Java 类型映射为相应的 JDBC 类型(遵循该 JDBCGuide中§8.6.2 “映射 Java 和 JDBC 类型”表中所指定的映射),并将该 JDBC 类型发送给数据库。
PreparedStatement & addBatch()
public static void main(String[] args) {
int id = 0;
String title = null;
try {
Class.forName("org.gjt.mm.mysql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","root");
conn.setAutoCommit(false);//禁用了自动执行模式,从而在调用 St.executeBatch() 时可以防止 JDBC 执行事务处理
//Statement st = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement("insert into aritcle values (?,?)");
//批处理
pstmt.setInt(1, id);
pstmt.setString(2, title);
pstmt.addBatch("");
//执行批处理
int [] counts = pstmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
pstmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}