说说Statement、PreparedStatement和CallableStatement的异同(转)

1.Statement、PreparedStatement和CallableStatement都是接口(interface)。 
2.Statement继承自Wrapper、PreparedStatement继承自Statement、CallableStatement继承自PreparedStatement。 
3. 
Statement接口提供了执行语句和获取结果的基本方法; 
PreparedStatement接口添加了处理 IN 参数的方法; 
CallableStatement接口添加了处理 OUT 参数的方法。 
4. 
a.Statement: 
普通的不带参的查询SQL;支持批量更新,批量删除; 
b.PreparedStatement: 
可变参数的SQL,编译一次,执行多次,效率高; 
安全性好,有效防止Sql注入等问题; 
支持批量更新,批量删除; 
c.CallableStatement: 
继承自PreparedStatement,支持带参数的SQL操作; 
支持调用存储过程,提供了对输出和输入/输出参数(INOUT)的支持; 

Statement每次执行sql语句,数据库都要执行sql语句的编译 , 
最好用于仅执行一次查询并返回结果的情形,效率高于PreparedStatement。 

PreparedStatement是预编译的,使用PreparedStatement有几个好处 
1. 在执行可变参数的一条SQL时,PreparedStatement比Statement的效率高,因为DBMS预编译一条SQL当然会比多次编译一条SQL的效率要高。 
2. 安全性好,有效防止Sql注入等问题。 
3.  对于多次重复执行的语句,使用PreparedStament效率会更高一点,并且在这种情况下也比较适合使用batch; 
4.  代码的可读性和可维护性。 

注: 
executeQuery:返回结果集(ResultSet)。 
executeUpdate: 执行给定SQL语句,该语句可能为 INSERT、UPDATE 或 DELETE 语句, 
或者不返回任何内容的SQL语句(如 SQL DDL 语句)。 
execute: 可用于执行任何SQL语句,返回一个boolean值, 
表明执行该SQL语句是否返回了ResultSet。如果执行后第一个结果是ResultSet,则返回true,否则返回false。 

Java代码 复制代码 收藏代码
    1. Statement用法:   
    2. String sql = "select seq_orderdetailid.nextval as test dual";   
    3. Statement stat1=conn.createStatement();   
    4. ResultSet rs1 = stat1.executeQuery(sql);   
    5. if ( rs1.next() ) {   
    6.     id = rs1.getLong(1);   
    7. }   
    8.   
    9. INOUT参数使用:   
    10. CallableStatement cstmt = conn.prepareCall("{call revise_total(?)}");   
    11. cstmt.setByte(1, 25);   
    12. cstmt.registerOutParameter(1, java.sql.Types.TINYINT);   
    13. cstmt.executeUpdate();   
    14. byte x = cstmt.getByte(1);   
    15.   
    16. Statement的Batch使用:   
    17. Statement stmt  = conn.createStatement();   
    18. String sql = null;   
    19. for(int i =0;i<20;i++){   
    20.     sql = "insert into test(id,name)values("+i+","+i+"_name)";   
    21.     stmt.addBatch(sql);   
    22. }   
    23. stmt.executeBatch();   
    24.   
    25. PreparedStatement的Batch使用:   
    26. PreparedStatement pstmt  = con.prepareStatement("UPDATE EMPLOYEES  SET SALARY = ? WHERE ID =?");   
    27. for(int i =0;i<length;i++){   
    28.     pstmt.setBigDecimal(1, param1[i]);   
    29.     pstmt.setInt(2, param2[i]);   
    30.     pstmt.addBatch();   
    31. }   
    32. pstmt.executeBatch();   
    33.   
    34. PreparedStatement用法:   
    35. PreparedStatement pstmt  = con.prepareStatement("UPDATE EMPLOYEES  SET SALARY = ? WHERE ID =?");   
    36. pstmt.setBigDecimal(1, 153.00);   
    37. pstmt.setInt(2, 1102);   
    38. pstmt. executeUpdate();  
posted @ 2015-12-23 10:41  java高级技术汇  阅读(249)  评论(0编辑  收藏  举报