jdbc批量处理数据

补充:只有开启事务才能达到最快,否则很慢
connection.setAutoCommit(false);//开启事务
connection.commit();//提交

package com.bq.siem;
 
import com.bq.siem.common.manager.DataBaseManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
 
public class Test {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        //DataBaseManager类是我自己封装的一个工具类,用于获取、关闭数据库资源,
        //大家如果只是自己测试用没必要,用DriverManager操作即可
        Connection connection= DataBaseManager.getConnection();
        
        //这里必须设置为false,我们手动批量提交
        connection.setAutoCommit(false);
        
        //这里需要注意,SQL语句的格式必须是预处理的这种,就是values(?,?,...,?),否则批处理不起作用
        PreparedStatement statement=connection.prepareStatement("insert into student(`name`,sex,age) values(?,?,?)");
 
        System.out.println("开始插入数据");
        Long startTime = System.currentTimeMillis();
        for (int i = 0; i <1000000 ; i++) {
    
    
            statement.setString(1,"小王");
            statement.setString(2,"男");
            statement.setInt(3,10);
            //将要执行的SQL语句先添加进去,不执行
            statement.addBatch();
        }
        //100W条SQL语句已经添加完成,执行这100W条命令并提交
        statement.executeBatch();
        connection.commit();
        Long endTime = System.currentTimeMillis();
        DataBaseManager.close(connection,statement);
        long milliseconds = endTime - startTime;
        long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds);
        System.out.format("插入完毕,用时:%d 毫秒 = %d 秒", milliseconds, seconds );
    }
}

参考:https://blog.csdn.net/wzy18210825916/article/details/88083395

猜你喜欢

转载自blog.csdn.net/weixin_48860638/article/details/121488683
今日推荐