使用PreparedStatement優化多行插入
最初,使用循環和單獨的PreparedStatement調用將行插入SQL表是一種常見的做法。然而,為了提高效能,最好利用 MySQL 支援的語法進行多行插入。
使用PreparedStatement 進行批次處理
PreparedStatement 提供了一個最佳化多行插入的解決方案。透過批次進行行插入。透過使用PreparedStatement#addBatch()方法,可以批次累積多個SQL語句。然後透過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. } } } }
其他資源
有關此技術的更多詳細信息,請參閱以下資源:
以上是PreparedStatement如何改進MySQL中的多行插入?的詳細內容。更多資訊請關注PHP中文網其他相關文章!