【实践】jdbc批量插入数据

参考文献:http://my.oschina.net/u/1452675/blog/203670

http://superjavason.iteye.com/blog/255423

 /*测试批量写入数据*/
long start = System.currentTimeMillis();
DaoRecord daoRecord = new DaoRecord();
List<T> list = new ArrayList<T>();
for(int i = 1; i <= 1000; i++){
for(int j = 1; j <= 1000; j++){
T t = new T();
t.setI(i);
t.setJ(j);
list.add(t);
}
}
daoRecord.InsertBatch(list);
System.out.println("耗时:" + (System.currentTimeMillis()-start)+"毫秒");
 //批量写入数据测试
public void InsertBatch(List<T> list){
String sql = "insert into t(go,back) values(?,?)";
DBHelper dbh = new DBHelper(sql);
Connection conn = dbh.returnConn();
try {
conn.setAutoCommit(false);//注意此句一定要为false,原因见第一篇参考文献
PreparedStatement ps = conn.prepareStatement(sql);
for(int i = 0; i < list.size(); i++){
ps.setInt(1, list.get(i).getI());
ps.setInt(2, list.get(i).getJ());
ps.addBatch();
if (i % 10000 == 0){
ps.executeBatch();
conn.commit();
}
}
ps.executeBatch();
conn.commit();
conn.close();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}

数据表:

【实践】jdbc批量插入数据

实验结果:

【实践】jdbc批量插入数据

上一篇:openfalcon源码分析之Judge


下一篇:移动Web开发调研