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

问题描述 投票:79回答:6

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

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

    myStatement.executeUpdate();
}

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

INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]

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

java mysql jdbc prepared-statement batch-insert
6个回答
155
投票

您可以通过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.
            }
        }
    }
}

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

也可以看看:


26
投票

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

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

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


5
投票

如果您可以动态创建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();

3
投票

如果您在表中有自动增量并需要访问它...您可以使用以下方法...在使用之前进行测试,因为它取决于使用的驱动程序,因为它在Statement中的getGeneratedKeys()。以下代码在Maria DB 10.0.12和Maria JDBC驱动程序1.2上进行了测试

请记住,增加批量大小只会在一定程度上提高性能...对于我的设置,增加批量大小超过500实际上会降低性能。

public Connection getConnection(boolean autoCommit) throws SQLException {
    Connection conn = dataSource.getConnection();
    conn.setAutoCommit(autoCommit);
    return conn;
}

private void testBatchInsert(int count, int maxBatchSize) {
    String querySql = "insert into batch_test(keyword) values(?)";
    try {
        Connection connection = getConnection(false);
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean success = true;
        int[] executeResult = null;
        try {
            pstmt = connection.prepareStatement(querySql, Statement.RETURN_GENERATED_KEYS);
            for (int i = 0; i < count; i++) {
                pstmt.setString(1, UUID.randomUUID().toString());
                pstmt.addBatch();
                if ((i + 1) % maxBatchSize == 0 || (i + 1) == count) {
                    executeResult = pstmt.executeBatch();
                }
            }
            ResultSet ids = pstmt.getGeneratedKeys();
            for (int i = 0; i < executeResult.length; i++) {
                ids.next();
                if (executeResult[i] == 1) {
                    System.out.println("Execute Result: " + i + ", Update Count: " + executeResult[i] + ", id: "
                            + ids.getLong(1));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (connection != null) {
                if (success) {
                    connection.commit();
                } else {
                    connection.rollback();
                }
                connection.close();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

3
投票

@Ali Shakiba你的代码需要一些修改。错误部分:

for (int i = 0; i < myArray.length; i++) {
     myStatement.setString(i, myArray[i][1]);
     myStatement.setString(i, myArray[i][2]);
}

更新的代码:

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(", (?, ?)");
}

mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());

for (int i = 0; i < myArray.length; i++) {
    myStatement.setString((2 * i) + 1, myArray[i][1]);
    myStatement.setString((2 * i) + 2, myArray[i][2]);
}

myStatement.executeUpdate();

0
投票

我们可以在JDBC中一起提交多个更新以提交批量更新。

我们可以使用Statement,PreparedStatement和CallableStatement对象进行批量更新,并禁用自动提交

addBatch()和executeBatch()函数可用于具有BatchUpdate的所有语句对象

这里addBatch()方法向当前批处理添加一组语句或参数。

© www.soinside.com 2019 - 2024. All rights reserved.