您的位置:首页 > 数据库

数据库插入大量数据性能测试——批处理+事务VS普通插入

2012-09-07 17:59 483 查看
测试:sql server插入10000行数据

关键代码(批处理+事务):

public void insertUser() {
String sql = "insert into users values(?,?)";
Connection conn = getConnection();
PreparedStatement ps = null;
try {
// 禁止自动提交事务
conn.setAutoCommit(false);
// 创建能返回自动生成的主键的值的预编译对象
ps = conn.prepareStatement(sql);
//开始时间的毫秒数
Long start=System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
ps.setString(1, i+"");
ps.setInt(2, 22);
ps.addBatch();// 添加到批处理命令中
}
ps.executeBatch();// 执行批处理
conn.commit();// 提交事务
//结束时间的毫秒数
Long stop=System.currentTimeMillis();
//得到总耗时
Long ms=stop-start;
System.out.println("插入一万记录耗时:"+ms+"毫秒");
} catch (SQLException e) {
e.printStackTrace();
//取消事务
try{
conn.rollback();
}catch(SQLException ee){
ee.printStackTrace();
}
} finally {
//打开自动提交事务
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
close(null, ps, conn);
}
}
结果:



关键代码(普通插入):

public void insertUser() {
String sql = "insert into users values(?,?)";
Connection conn = getConnection();
PreparedStatement ps = null;
try {
// 创建能返回自动生成的主键的值的预编译对象
ps = conn.prepareStatement(sql);
//开始时间的毫秒数
Long start=System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
ps.setString(1, i+"");
ps.setInt(2, 22);
ps.executeUpdate();
}
//结束时间的毫秒数
Long stop=System.currentTimeMillis();
//得到总耗时
Long ms=stop-start;
System.out.println("插入一万记录耗时:"+ms+"毫秒");
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(null, ps, conn);
}
}
结果:



最后:差距还是挺大的!现在见识批处理和事务的高效了吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: