package blob; import java.sql.Connection; import java.sql.PreparedStatement; import jdbc.utils.*; //使用PreparedStatement實現更高效的批量插入 //如果不能使用batch方法,在url最后添加 ?rewriteBatchedStatements=true public class InsertTest { static public void testInsert2() { Connection con = null; PreparedStatement ps = null; try { con = JDBCUtils.getConnection(); String sql = "insert into good values(?,?)"; ps = con.prepareStatement(sql); //不允許自動提交數據 con.setAutoCommit(false); for(int i=1;i<=20000;i++) { ps.setInt(1, i); ps.setString(2, "good_"); ps.addBatch();//使用批處理Batch來暫存數據 if(i%500 == 0) {//再一起放到數據庫里 ps.executeBatch(); ps.clearBatch(); } } //最后統一提交數據 con.commit(); } catch(Exception ex) { ex.printStackTrace(); } finally { JDBCUtils.closeResource(con, ps); } } public static void main(String[]args) { testInsert2(); } }
1