【问题标题】:Fastest way to insert thousands of rows into mysql database?将数千行插入mysql数据库的最快方法?
【发布时间】:2012-11-27 08:19:12
【问题描述】:

谁能建议将数千/数十万行插入 mysql 表的最快方法?现在我正在使用 executeBatch,但我想知道是否有更快的方法来做到这一点?

try {
        Connection con = dataSource.getConnection();
        Statement statement = con.createStatement();


        for(int i = 0; i < value; i++) {
            DateTime f = DateTime.now().minusDays(i % 28);
            String q1 = "INSERT INTO table1_test (txid, time, badgeid, event_type, sensorid, shift, unitid) VALUES ('"+i+"', '"+f.toString("yyyy-MM-dd HH:mm:ss")+"', 'NA', 'EN', '100', 'A', '1')";
            String q2 = "INSERT INTO table2_test (txid, time, badgeid, sensorid, shift, unitid) VALUES ('"+i+"', '"+f.toString("yyyy-MM-dd HH:mm:ss")+"', 'NA', '100', 'A', '1')";
            String q3 = "INSERT INTO table3_test (txid, badgeid, time, shift, compliant, sensorid, unitid) VALUES ('"+i+"', 'NA', '"+f.toString("yyyy-MM-dd HH:mm:ss")+"', 'A', 1, '100', '1')";
            statement.addBatch(q1);
            statement.addBatch(q2);
            statement.addBatch(q3);
        }
        statement.executeBatch();
        statement.close();
        con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

【问题讨论】:

  • 考虑在一个插入语句中将多行合并到同一个表中。否则,Prepared Statements 是您的最佳选择。

标签: java mysql optimization


【解决方案1】:

尝试使用 'LOAD DATA INFILE' 查询类型将数据导入数据库。我认为,使用 jdbc 也应该可以。

【讨论】:

  • LOAD DATA INFILE 不是复制安全的。最好的办法是批量插入。
猜你喜欢
  • 2016-02-03
  • 2016-08-12
  • 2016-04-20
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多