如何使用 Java 生成多個插入查詢?
JDBC 提供了一種稱為批次處理的機制,您可以將一組 INSERT、UPDATE 或 DELETE 命令(這些命令會產生更新計數值)組合在一起,並立即執行它們。您可以使用此方法將多條記錄插入表中。
向批處理新增語句
Statement、PreparedStatement 和 CallableStatement 物件儲存一個命令列表,您可以使用 **addBatch()** 方法向其中新增相關的語句(這些語句返回更新計數值)。
stmt.addBatch(insert1); stmt.addBatch(insert2); stmt.addBatch(insert3);
執行批處理
新增所需的語句後,您可以使用 Statement 介面的 executeBatch() 方法執行批處理。
stmt.executeBatch();
使用批處理更新,我們可以減少通訊開銷並提高 Java 應用程式的效能。
**注意:**在向批處理新增語句之前,您需要使用 **con.setAutoCommit(false)** 關閉自動提交,並在執行批處理後,您需要使用 **con.commit()** 方法儲存更改。
讓我們使用如下所示的 CREATE 語句在 MySQL 資料庫中建立一個名為 **sales** 的表:
CREATE TABLE sales( Product_Name varchar(255), Name_Of_Customer varchar(255), Month_Of_Dispatch varchar(255), Price int, Location varchar(255) );
下面的 JDBC 程式嘗試使用批處理更新將一組語句插入到上述表中。
示例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BatchUpdates {
public static void main(String args[])throws Exception {
//Getting the connection
String mysqlUrl = "jdbc:mysql:///sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement();
//Setting auto-commit false
con.setAutoCommit(false);
//Statements to insert records
String insert1 = "INSERT INTO Dispatches VALUES ('KeyBoard', 'Amith', 'January', 1000, 'Hyderabad')";
String insert2 = "INSERT INTO Dispatches VALUES ('Earphones', 'SUMITH', 'March', 500, 'Vishakhapatnam')";
String insert3 = "INSERT INTO Dispatches VALUES ('Mouse', 'Sudha', 'September', 200, 'Vijayawada')";
//Adding the statements to batch
stmt.addBatch(insert1);
stmt.addBatch(insert2);
stmt.addBatch(insert3);
//Executing the batch
stmt.executeBatch();
//Saving the changes
con.commit();
System.out.println("Records inserted......");
}
}輸出
Connection established...... Records inserted......
如果您驗證表的內容,您可以在其中找到插入的記錄,如下所示:
+--------------+------------------+-------------------+-------+----------------+ | Product_Name | Name_Of_Customer | Month_Of_Dispatch | Price | Location | +--------------+------------------+-------------------+-------+----------------+ | KeyBoard | Amith | January | 1000 | Hyderabad | | Earphones | SUMITH | March | 500 | Vishakhapatnam | | Mouse | Sudha | September | 200 | Vijayawada | +--------------+------------------+-------------------+-------+----------------+
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP