首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

说说Statement、PreparedStatement跟CallableStatement的异同

2012-09-10 
说说Statement、PreparedStatement和CallableStatement的异同.1.Statement、PreparedStatement和CallableSta

说说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。

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();

热点排行