使用JDBC操作数据库时,可以使用 PreparedStatement 的 addBatch() 批量执行方法,测试代码如下,有个特别注意的地方
当要批量插入时最后把自动提交去掉,不然效率会低很多。
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", 你的数据库密码);
connection.setAutoCommit(false);
long start = System.currentTimeMillis();
String sql = "insert into users(username, password) values(?, ?)";
preparedStatement = connection.prepareStatement(sql);
for(int i = 1; i <= 2000; i++) {
preparedStatement.setString(1, "z" + i);
preparedStatement.setString(2, "qwe" + i);
preparedStatement.addBatch();
//分批执行
if(i % 200 == 0) {
preparedStatement.executeBatch();
//清空batch空间
preparedStatement.clearBatch();
}
}
System.out.println(System.currentTimeMillis() - start);
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
close(connection, preparedStatement);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public static void close(Connection connection, PreparedStatement preparedStatement) throws SQLException{
if(preparedStatement != null) {
preparedStatement.close();
}
if(connection != null) {
connection.close();
}
}
自动提交所消耗时间 62231 毫秒
如果设置了手动提交,时间会减很多 只有 329 毫秒
所以如果用了批量功能,必须设置成手动提交,要不然跟你一条一条插入是没有什么区别的