JDBC插入多行

DrX*_*eng 34 java mysql jdbc batch-file

我现在正在使用批处理:

String query = "INSERT INTO table (id, name, value) VALUES (?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(query);            
for (Record record : records) {
    ps.setInt(1, record.id);
    ps.setString(2, record.name);
    ps.setInt(3, record.value);
    ps.addBatch();
}
ps.executeBatch();
Run Code Online (Sandbox Code Playgroud)

我只是想知道上面的代码是否等同于以下代码.如果没有,哪个更快?

String query = "INSERT INTO table (id, name, value) VALUES ";
for (Record record : records) {
    query += "(" + record.id + ",'" + record.name + "'," + record.value + "),";
}
query = query.substring(1, query.length() - 1);
PreparedStatement ps = connection.prepareStatement(query);
ps.executeUpdate();
Run Code Online (Sandbox Code Playgroud)

Rei*_*eus 37

executeBatchexecuteUpdate只要自动提交设置为false,就会有更好的性能:

connection.setAutoCommit(false);  
PreparedStatement ps = connection.prepareStatement(query);            
for (Record record : records) {
    // etc.
    ps.addBatch();
}
ps.executeBatch();
connection.commit(); 
Run Code Online (Sandbox Code Playgroud)

  • 完成后我们应该将 autoCommit 设置回 true 吗? (2认同)

Fil*_*lto 25

首先,使用查询字符串连接,您不仅会丢失PreparedStatement方法的原生类型转换,而且还容易受到在数据库中执行的恶意代码的攻击.

其次,PreparedStatements以前被缓存在数据库本身中,这已经比普通语句提供了非常好的性能改进.


Mem*_*min 5

如果要插入的项目数量很大,您可能会面临严重的性能问题。因此,定义一个批大小,并在达到批大小时不断执行查询会更安全。

像下面的示例代码这样的东西应该可以工作。有关如何有效使用此代码的完整故事,请参阅此链接

private static void insertList2DB(List<String> list) {
        final int batchSize = 1000; //Batch size is important.
        Connection conn = getConnection();
        PreparedStatement ps = null;
        try {
            String sql = "INSERT INTO theTable (aColumn) VALUES (?)";
            ps = conn.prepareStatement(sql);

            int insertCount=0;
            for (String item : list) {
                ps.setString(1, item);
                ps.addBatch();
                if (++insertCount % batchSize == 0) {
                    ps.executeBatch();
                }
            }
            ps.executeBatch();

        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }
    finally {
        try {
            ps.close();
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)