Java:使用PreparedStatement在MySQL中插入多行

Tom*_*nal 83 java mysql jdbc prepared-statement batch-insert

我想使用Java一次将多行插入MySQL表.行数是动态的.过去我在做......

for (String element : array) {
    myStatement.setString(1, element[0]);
    myStatement.setString(2, element[1]);

    myStatement.executeUpdate();
}
Run Code Online (Sandbox Code Playgroud)

我想优化它以使用MySQL支持的语法:

INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]
Run Code Online (Sandbox Code Playgroud)

但是PreparedStatement我不知道有什么方法可以做到这一点,因为我事先不知道array会包含多少元素.如果a不可能PreparedStatement,我还能怎么做(并且仍然逃避数组中的值)?

Bal*_*usC 164

您可以通过创建批处理PreparedStatement#addBatch()并执行它PreparedStatement#executeBatch().

这是一个启动示例:

public void save(List<Entity> entities) throws SQLException {
    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setString(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它每1000个项目执行一次,因为某些JDBC驱动程序和/或DB可能对批处理长度有限制.

另见:

  • 如果你把它们放在事务中你的插入会更快...即用`connection.setAutoCommit(false);`和`connection.commit();`http://download.oracle.com/javase/tutorial/jdbc换行/basics/transactions.html (26认同)
  • @electricalbah它会正常执行,因为`i == entities.size()` (2认同)

小智 29

使用MySQL驱动程序时,必须将连接参数设置rewriteBatchedStatements为true ( jdbc:mysql://localhost:3306/TestDB?**rewriteBatchedStatements=true**).

使用此参数,当表仅锁定一次且索引仅更新一次时,语句将重写为批量插入.所以它要快得多.

没有这个参数,唯一的优势就是更清晰的源代码.


Ali*_*iba 6

如果您可以动态创建sql语句,则可以执行以下解决方法:

    String myArray[][] = { { "1-1", "1-2" }, { "2-1", "2-2" },
            { "3-1", "3-2" } };

    StringBuffer mySql = new StringBuffer(
            "insert into MyTable (col1, col2) values (?, ?)");

    for (int i = 0; i < myArray.length - 1; i++) {
        mySql.append(", (?, ?)");
    }

    myStatement = myConnection.prepareStatement(mySql.toString());

    for (int i = 0; i < myArray.length; i++) {
        myStatement.setString(i, myArray[i][1]);
        myStatement.setString(i, myArray[i][2]);
    }
    myStatement.executeUpdate();
Run Code Online (Sandbox Code Playgroud)

  • 我相信接受的答案要好得多!我不知道批量更新,当我开始写这个答案时,答案还没有提交!:) (2认同)