使用JDBC高效批量新增数据

package com.sitech.ddoe.test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class BatchInsertTest {

    private String insertSql;
    private String connectUrl;
    private String username;
    private String password;
    // 每commitNum提交一次
    private int commitNum = 6000;

    public BatchInsertTest() {
        connectUrl = "jdbc:mysql://ip:port/dbname";
        connectUrl += "?useServerPrepStmts=false&rewriteBatchedStatements=true";
        insertSql = "INSERT INTO log_performance (msg_id,consume_time) " + " VALUE (?,?)";
        username = "****";
        password = "****";
    }

    public static void main(String[] args) throws IOException {
        String srcFile = "D:/Temp/log/performance-analysis.log";
        Long beginTime = System.currentTimeMillis();
        new BatchInsertTest().storeToDb(srcFile);
        long time = System.currentTimeMillis() - beginTime;
        System.out.println("Consume time :" + String.valueOf(time / 1000) + "s");
    }

    public void storeToDb(String srcFile) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile)));
        try {
            doStore(reader);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reader.close();
        }
    }

    private void doStore(BufferedReader reader) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(connectUrl, username, password);
        conn.setAutoCommit(false); // 设置手动提交
        int count = 0;
        PreparedStatement ps = conn.prepareStatement(insertSql);
        String str = null;
        while (null != (str = reader.readLine())) {
            String[] s = str.substring(str.indexOf("]") + 2).split("-");
            ps.setLong(1, Long.valueOf(s[0]));
            ps.setLong(2, Long.valueOf(s[1]));
            ps.addBatch();
            count++;
            // 每commitNum条记录插入一次
            if (count % commitNum == 0) {
                ps.executeBatch();
                conn.commit();
            }
        }
        ps.executeBatch();
        conn.commit();
        System.out.println("All down : " + count);
        conn.close();
    }

}

文章出处:

使用JDBC在MySQL数据库中快速批量插入数据

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值