package cn.Pdispose; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import cn.paging.JdbcUtil; //批处理 public class Dispose { private static Connection conn = null; private static Statement st = null; private static PreparedStatement ps = null; public static void testInsert(){ try { conn = JdbcUtil.getConnection(); st = conn.createStatement(); String sql1 = "insert into t_name(id,name) values(1,'jing')"; String sql2 = "insert into t_name(id,name) values(2,'zhang')"; String sql3 = "delete from t_name where id = 1"; //addBatch()内部为一个list,加到list中 st.addBatch(sql1); st.addBatch(sql2); st.addBatch(sql3); //元素师每条语句影响到的行数 int [] i = st.executeBatch(); for(int num : i){ System.out.println(num); } } catch (SQLException e) { e.printStackTrace(); }finally{ JdbcUtil.closeJdbc(conn, null, ps); } } //同一时候在一个表里边插入100条数据 //因为语句全然同样。仅仅是參数不同。使用PreparedStatement public static void testInsert_1(){ long date = System.currentTimeMillis(); try { conn = JdbcUtil.getConnection(); String sql = "insert into t_name values(?,?)"; ps = conn.prepareStatement(sql); for(int i=1;i<=100;i++){ ps.setInt(1, i); ps.setString(2, "date---"+i); //将一组參数加入到此 PreparedStatement 对象的批处理命令中。 ps.addBatch(); } //将一批命令提交给数据库来运行。假设所有命令运行成功,则返回更新计数组成的数组。 ps.executeBatch(); } catch (SQLException e) { e.printStackTrace(); }finally{ JdbcUtil.closeJdbc(conn, null, ps); } System.out.println("用时:"+((System.currentTimeMillis()-date)/1000)+"秒"); } //想数据库中插入10000条数据,并设置缓存区 public static void testInsert_2(){ //初始化一个时间 long time = System.currentTimeMillis(); try { conn = JdbcUtil.getConnection(); String sql = "insert into t_name values(?
,?)";
ps = conn.prepareStatement(sql);for(int i=1;i<1000001;i++){ ps.setInt(1, i);ps.setString(2, "date"+i);ps.addBatch();if(i%1000==0){ ps.executeBatch();ps.clearBatch();//清空数据}}ps.executeBatch();} catch (SQLException e) { e.printStackTrace();}finally{ JdbcUtil.closeJdbc(conn, null, ps);}System.out.println("用时:"+((System.currentTimeMillis()-time)/1000)+"秒");}public static void main(String[] args) { testInsert_2();} }版权声明:本文博主原创文章,博客,未经同意不得转载。