编写一个示例 JDBC 程序,演示如何使用 PreparationStatement 对象进行批处理?
将相关的 SQL 语句分组为一个批处理并一次性执行/提交,这被称为批处理。Statement 接口提供了执行批处理的方法,例如 addBatch()、executeBatch() 和 clearBatch()。
按照以下步骤使用 PreparationStatement 对象执行批量更新:
使用 DriverManager 类的 registerDriver() 方法注册驱动程序类。并将驱动程序类名称作为参数传递给它。
使用 DriverManager 类的 getConnection() 方法连接到数据库。将 URL(字符串)、用户名(字符串)、密码(字符串)作为参数传递给它。
使用 Connection 接口的 setAutoCommit() 方法将自动提交设置为 false。
使用 Connection 接口的 prepareStatement() 方法创建一个 PreparationStatement 对象。向其传递一个包含占位符 (?) 的查询 (insert)。
使用 PreparedStatement 接口的 setter 方法将值设置为上述创建的语句中的占位符。
使用 Statement 接口的 addBatch() 方法将所需的语句添加到批处理中。
使用 executeBatch() 方法执行批处理。的 Statement 接口。
使用 Statement 接口的 commit() 方法提交所做的更改。
示例:
假设我们创建了一个名为 Dispatches 的表,其描述为
+-------------------+--------------+------+-----+---------+-------+ | 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.PreparedStatement;
public class BatchProcessing_PreparedStatement {
public static void main(String args[])throws Exception {
//获取连接
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("连接已建立......");
//设置自动提交为 false
con.setAutoCommit(false);
//创建PreparedStatement对象
PreparedStatement pstmt = con.prepareStatement("INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?)");
pstmt.setString(1, "Keyboard");
pstmt.setString(2, "Amith");
pstmt.setString(3, "January");
pstmt.setInt(4, 1000);
pstmt.setString(5, "Hyderabad");
pstmt.addBatch();
pstmt.setString(1, "Earphones");
pstmt.setString(2, "Sumith");
pstmt.setString(3, "March");
pstmt.setInt(4, 500);
pstmt.setString(5,"Vishakhapatnam");
pstmt.addBatch();
pstmt.setString(1, "Mouse");
pstmt.setString(2, "Sudha");
pstmt.setString(3, "September");
pstmt.setInt(4, 200);
pstmt.setString(5, "Vijayawada");
pstmt.addBatch();
//执行批处理
pstmt.executeBatch();
//保存更改
con.commit();
System.out.println("Records inserted......");
}
}
输出
连接已建立...... Records inserted......
如果您验证 Dispatches 表的内容,您可以观察到插入的记录如下:
+--------------+------------------+-------------------+-------+----------------+ | 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 | +--------------+------------------+-------------------+-------+----------------+

