JDBC 批量存入数据库

使用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   毫秒

        所以如果用了批量功能,必须设置成手动提交,要不然跟你一条一条插入是没有什么区别的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值