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()**方法保存更改。
示例
假设我们在数据库中创建了一个名为Sales的表,其描述如下:
+-------------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------------+--------------+------+-----+---------+-------+ | Product_Name | varchar(255) | YES | | NULL | | | Name_Of_Customer | varchar(255) | YES | | NULL | | | Month_Of_Dispatch | varchar(255) | YES | | NULL | | | Price | int(11) | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +-------------------+--------------+------+-----+---------+-------+
此示例尝试使用批量更新将一组语句插入到上述表中。
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://127.0.0.1/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 | +--------------+------------------+-------------------+-------+----------------+
广告