每次新建Connection的时候相当于建了一座桥,每次一辆车(PreparedStatement)运送货物(ResultSet)成本太高!
每次都建立网络连接的时间远远大于本地的时间,为了处理大量的数据
所以将数据打包,然后发送
static void createBatch() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "insert into user(name,birthday, money) values (?, ?, ?) ";
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 + i);
ps.addBatch();//打包
}
int[] is = ps.executeBatch();//执行这个包
} finally {
JdbcUtils.free(rs, ps, conn);
}
}