使用JDBC语句批量插入
将一组INSERT语句分组并立即执行它们被称为批处理插入。
使用Statement对象进行批量插入
使用Statement对象执行一批插入语句-
将语句添加到批处理中-准备INSERT逐一查询,然后使用Statement接口的addBatch()方法将它们添加到批处理中,如下所示-
String insert1 = Insert into table_name values(value1, value2, value3, ......); stmt.addBatch(insert1); String insert2 = Insert into table_name values(value1, value2, value3, ......); stmt.addBatch(insert2); String insert3 = Insert into table_name values(value1, value2, value3, ......); stmt.addBatch(insert3);
执行批处理-添加必需的语句后,您需要使用Statement接口的executeBatch()方法执行批处理。
stmt.executeBatch();
使用批处理插入,我们可以减少通信开销并提高Java应用程序的性能。
注–在将语句添加到批处理之前,您需要使用con.setAutoCommit(false)关闭自动提交,并且在执行批处理之后,需要使用con.commit()方法保存更改。
示例
让我们使用CREATE语句在MySQL数据库中创建一个名称为Dispatches的表,如下所示-
CREATE table Dispatches ( Product_Name, varchar(255) Name_Of_Customer, varchar(255) Month_Of_Dispatch, varchar(255) Price, int(11) Location, varchar(255) );
以下JDBC程序尝试使用Statement对象批量执行一堆INSERT语句。
示例
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 | +--------------+------------------+-------------------+-------+----------------+
