使用线程进行记录插入的最佳做法?

rma*_*aik 3 java sqlite multithreading jdbc executorservice

我想用超过5亿行填充数据库表,我有以下insert方法:

public void insertRecord(Record rec) throws SQLException, ClassNotFoundException {

    if (this.isTableExists(this.TABLE_NAME)) {

        Connection conn = this.getConnection();
        conn.setAutoCommit(true);
        PreparedStatement ps = conn.prepareStatement("insert into "+this.TABLE_NAME+" ("+this.NODE_ID_COL+", "+this.LAT_COL+", "+this.LNG_COL+", "+this.XML_PATH_COL+") values (?, ?, ?, ?)");

        ps.setString(1, rec.getNodeID());
        ps.setString(2, rec.getLat());
        ps.setString(3, rec.getLng());
        ps.setString(4, rec.getPath());

        ps.addBatch();
        ps.executeBatch();

        ps.close();
        conn.close();

    } else {
        Log.e(TAG, "insertRecord", "table: ["+this.TABLE_NAME+"] does not exist");
    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是,因为我将插入大量的行:

  1. 我应该在上面发布的方法中使用线程吗?
  2. 这种情况的最佳做法是什么?
  3. 在这种情况下,ExecutorService会产生更好的表现吗?

Kay*_*man 5

你的方法效率很低.对于每个记录你

  1. 获取新连接(如果您有连接池,这不是问题)
  2. 准备一个新的 PreparedStatement
  3. 创建一批大小为1的批次
  4. 立即执行批处理

相反,你应该保持一个单独的PreparedStatement并执行50-100的批量.

之后,如果你知道你在做什么,你可以考虑多线程.多线程并不能让一切变得更快.