区别
1. Statement、PreparedStatement和CallableStatement都是接口(interface)。
2. Statement继承自Wrapper、PreparedStatement继承自Statement、CallableStatement继承自PreparedStatement。
3. Statement 每次执行sql语句,数据库都要执行sql语句的编译 ,最好用于仅执行一次查询并返回结果的情形,效率高于PreparedStatement.
4. PreparedStatement是预编译的,使用PreparedStatement有几个好处a. 在执行可变参数的一条SQL时,PreparedStatement比Statement的效率高,因为DBMS预编译一条SQL当然会比多次编译一条SQL的效率要高。
b. 安全性好,有效防止Sql注入等问题。
c. 对于多次重复执行的语句,使用PreparedStament效率会更高一点,并且在这种情况下也比较适合使用batch;
d. 代码的可读性和可维护性。
3. CallableStatement接口扩展 PreparedStatement,用来调用存储过程,它提供了对输出和输入/输出参数的支持。CallableStatement 接口还具有对 PreparedStatement 接口提供的输入参数的支持。
代码案例
Statement用法:
String sql = "select seq_orderdetailid.nextval as test dual";
Statement stat1=conn.createStatement();
ResultSet rs1 = stat1.executeQuery(sql);
if ( rs1.next() ) {
id = rs1.getLong(1);
}
INOUT参数使用:
CallableStatement cstmt = conn.prepareCall("{call revise_total(?)}");
cstmt.setByte(1, 25);
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.executeUpdate();
byte x = cstmt.getByte(1);
Statement的Batch使用:
Statement stmt = conn.createStatement();
String sql = null;
for(int i =0;i<20;i++){
sql = "insert into test(id,name)values("+i+","+i+"_name)";
stmt.addBatch(sql);
}
stmt.executeBatch();
PreparedStatement的Batch使用:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID =?");
for(int i =0;i<length;i++){
pstmt.setBigDecimal(1, param1[i]);
pstmt.setInt(2, param2[i]);
pstmt.addBatch();
}
pstmt.executeBatch();
PreparedStatement用法:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID =?");
pstmt.setBigDecimal(1, 153.00);
pstmt.setInt(2, 1102);
pstmt.executeUpdate()