如何通过 java 生成多个插入查询?
jdbcjava 8object oriented programmingprogramming
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 { //获取连接 String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建Statement对象 Statement stmt = con.createStatement(); //设置自动提交为false con.setAutoCommit(false); //插入记录的语句 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')"; //将语句添加到批处理 stmt.addBatch(insert1); stmt.addBatch(insert2); stmt.addBatch(insert3); //执行批处理 stmt.executeBatch(); //保存更改 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 | +--------------+------------------+-------------------+-------+----------------+