Java:使用PreparedStatement在MySQL中插入多行我想使用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会包含多少元素。如果a不可能PreparedStatement,我还能怎么做(并且仍然逃避数组中的值)?
3 回答
慕虎7371278
TA贡献1802条经验 获得超4个赞
您可以通过创建批处理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可能对批处理长度有限制。
另见:
守着星空守着你
TA贡献1799条经验 获得超8个赞
如果您可以动态创建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();添加回答
举报
0/150
提交
取消
