我想使用 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
,我还能怎么做(并且仍然转义数组中的值)?
您可以通过以下方式创建批次PreparedStatement#addBatch() http://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#addBatch--并执行它PreparedStatement#executeBatch() http://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#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 可能对批处理长度有限制。
See also:
- JDBC 教程 - 使用PreparedStatement http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
- JDBC 教程 - 使用 Statement 对象进行批量更新 https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html#batch_updates
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)