采用批处理之前
public static void create(int i) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getinstance().getConnection();
String sql = "insert into user(name, birthday, money) value (?, ?, ?)";
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "batch name" + i);
ps.setDate(2, new Date(System.currentTimeMillis()));
ps.setFloat(3, 100f);
ps.executeUpdate(sql);
} finally {
// 6.释放资源
jdbcUtils.free(rs, ps, conn);
}
}
采用批处理之后
public static void createBatch() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getinstance().getConnection();
String sql = "insert into user(name, birthday, money) value (?, ?, ?)";
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < 100; i++) {
ps.setString(1, "batch name" + i);
ps.setDate(2, new Date(System.currentTimeMillis()));
ps.setFloat(3, 100f);
ps.addBatch();
}
ps.executeUpdate(sql);
} finally {
// 6.释放资源
jdbcUtils.free(rs, ps, conn);
}
}
两者比较
public static void main(String[] args) throws SQLException {
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
create(i);
}
long end = System.currentTimeMillis();
System.out.println("Create:" + (end - start));
start = System.currentTimeMillis();
end = System.currentTimeMillis();
System.out.println("CreateBratch:" + (end - start));
}
执行结果
Create:3641
CreateBratch:2734