执行SQL语句
调用Connection的createStatement方法创建语句对象。
调用Statement的executeUpdate方法执行SQL语句。
关闭语句对象。
stmt.close();
预编译语句是只编译和优化一次,然后可以通过设置不同的参数值多次使用。由于已经预先编译好,后续使用会减少执行时间。因此,如果多次执行一条语句,请选择使用预编译语句。可以按以下步骤执行:
调用Connection的prepareStatement方法创建预编译语句对象。
PreparedStatement pstmt = con.prepareStatement("UPDATE customer_t1 SET c_customer_name = ? WHERE c_customer_sk = 1");
调用PreparedStatement的setShort设置参数。
pstmt.setShort(1, (short)2);
调用PreparedStatement的executeUpdate方法执行预编译SQL语句。
调用PreparedStatement的close方法关闭预编译语句对象。
调用Connection的prepareCall方法创建调用语句对象。
Connection myConn = DriverManager.getConnection("url","user","password");
调用CallableStatement的setInt方法设置参数。
cstmt.setInt(2, 50);
cstmt.setInt(1, 20);
cstmt.setInt(3, 90);
调用CallableStatement的registerOutParameter方法注册输出参数。
cstmt.registerOutParameter(4, Types.INTEGER); //注册out类型的参数,类型为整型。
调用CallableStatement的execute执行方法调用。
cstmt.execute();
调用CallableStatement的getInt方法获取输出参数。
示例:
用一条预处理语句处理多条相似的数据,数据库只创建一次执行计划,节省了语句的编译和优化时间。可以按如下步骤执行:
调用Connection的prepareStatement方法创建预编译语句对象。
Connection conn = DriverManager.getConnection("url","user","password");
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO customer_t1 VALUES (?)");
针对每条数据都要调用setShort设置参数,以及调用addBatch确认该条设置完毕。
pstmt.setShort(1, (short)2);
pstmt.addBatch();
调用PreparedStatement的executeBatch方法执行批处理。