private void function1(List<Test> list){
SqlMapClient client = super.getSqlMapClient();
Connection conn = null;
try{
client.startTransaction();
conn = client.getCurrentConnection();
conn.setAutoCommit(false);
PreparedStatement ps = null;
ps = conn.prepareStatement("insert into test
(t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15) values
(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
for(int i = 0; i<list.size(); i++){
Test t = list.get(i);
ps.setString(1, t.getT1());
ps.setString(2, t.getT2());
ps.setString(3, t.getT3());
ps.setString(4, t.getT4());
ps.setString(5, t.getT5());
ps.setString(6, t.getT6());
ps.setString(7, t.getT7());
ps.setString(8, t.getT8());
ps.setString(9, t.getT9());
ps.setString(10, t.getT10());
ps.setString(11, t.getT11());
ps.setString(12, t.getT12());
ps.setString(13, t.getT13());
ps.setString(14, t.getT14());
ps.setString(15, t.getT15());
ps.execute();
}
conn.commit();
client.commitTransaction();
}catch(SQLException e){
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
try {
client.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
}function1在处理10000条数据入库时用了3S,效率高。
其可靠性强吗? 这个语句中的conn = client.getCurrentConnection();
能够可靠的取得conn实例吗,api上面说这个方法在一定条件下回返回null,
这个条件是什么样的呢?还有就是conn我不关闭它会回答连接池中吗? private void function2(List<Test> list){
SqlMapClient client = super.getSqlMapClient();
try {
client.startTransaction();
client.startBatch();
for(int i = 0; i<list.size(); i++){
client.insert("TreeNode.test", list.get(i));
} // 执行批处理
client.executeBatch();
client.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
client.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
}function2在处理10000条数据入库时用了11s-12s;
效率较低请教function2有优化方案吗?
综上,function1好还是function2好?
fuction2 插入速度和 JDBC 差不多~
你只需要在循环里面加一个 if(i%300 == 0) client.executeBatch();
我想这样 速度就差不多了~
尽量用框架性质的玩意,以后方便改代码