Statement及PreparedStatement執行多個sql


    這兩個對象的區別:
1.Statement它更適合執行不同sql的批處理,它沒有提供預處理功能,性能比較低。
2.PreparedStatement它適合執行相同的批處理,它提供了預處理功能,屬性比較高。 
          /**
      * @param args
      * @throws SQLException
      * @throws ClassNotFoundException
      */
      public static void main(String[] args) throws ClassNotFoundException,
                SQLException {
            // 定義sql 語句
           String sql1 = "create table person(id int,name varchar(20))" ;
           String sql2 = "insert into person values(1,'tom')" ;
           String sql3 = "insert into person values(2,'fox')" ;
           String sql4 = "insert into person values(3,'tony')" ;
           String sql5 = "update person set name='張三' where id=1" ;
           String sql6 = "delete from person where id=3" ;
 
           Connection conn = jdbcUtils.getConnection();
           Statement st = conn.createStatement();
 
            // 添加批處理sql
           st.addBatch(sql1);
           st.addBatch(sql2);
           st.addBatch(sql3);
           st.addBatch(sql4);
           st.addBatch(sql5);
           st.addBatch(sql6);
 
            // 執行批處理sql
           st.executeBatch();
           st.clearBatch();
           st.close();
            conn.close();
 
     }
 
 
使用版本高一點的 jdbc的jar包時加入參數可開啟緩存在url中加參數:
?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true
      /**
      * @param args
      * @throws SQLException
      * @throws ClassNotFoundException
      */
      public static void main(String[] args) throws ClassNotFoundException,
                SQLException {
           String sqlString = "insert into person values(?,?)" ;
           Connection conn = jdbcUtils. getConnection();
           PreparedStatement pst = conn.prepareStatement(sqlString);
            long l = System. currentTimeMillis();
            for ( int i = 0; i < 10000; i++) {
                pst.setInt(1, i);
                pst.setString(2, "name" + i);
                pst.addBatch();
                 if (i % 1000 == 0) {
                     pst.executeBatch();
                     pst.clearBatch(); // 清空緩存
                }
           }
           pst.executeBatch();
           pst.close();
           conn.close();
           System. out .println(System. currentTimeMillis() - l);
     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM