1. 程式人生 > >JDBC之Statement,PreparedStatement,CallableStatement的區別

JDBC之Statement,PreparedStatement,CallableStatement的區別

div html border pad plain lai conn delet pes

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。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 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()

JDBC之Statement,PreparedStatement,CallableStatement的區別