Java:使用PreparedStatement在MySQL中插入多行我想使用Java一次將多行插入MySQL表。行數(shù)是動態(tài)的。過去我在做......for (String element : array) {
myStatement.setString(1, element[0]);
myStatement.setString(2, element[1]);
myStatement.executeUpdate();}我想優(yōu)化它以使用MySQL支持的語法:INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]但是PreparedStatement我不知道有什么方法可以做到這一點,因為我事先不知道array會包含多少元素。如果a不可能PreparedStatement,我還能怎么做(并且仍然逃避數(shù)組中的值)?
3 回答

慕虎7371278
TA貢獻1802條經(jīng)驗 獲得超4個贊
您可以通過創(chuàng)建批處理PreparedStatement#addBatch()
并執(zhí)行它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個項目執(zhí)行一次,因為某些JDBC驅(qū)動程序和/或DB可能對批處理長度有限制。
另見:

守著星空守著你
TA貢獻1799條經(jīng)驗 獲得超8個贊
如果您可以動態(tài)創(chuàng)建sql語句,則可以執(zhí)行以下解決方法:
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
提交
取消