Java中的批处理用于执行一组查询或批处理,因为一次又一次地执行单个查询会浪费时间并降低性能。因此,使用批处理可以一次执行多个查询。这样可以提高程序的性能。
批处理可以通过使用Java的Statement和Prepared Statement来完成,因为这两个语句提供了用于处理批处理的批处理方法。
我们有两种批处理方法:
void addBatch(String query):此函数将查询添加到批处理中。
int [] executeBatch()
:此函数执行批处理。
让我们举个例子来看一下批处理是如何完成的?
在这里,我们以employee表为例,我们将在其中插入多个雇员的多个字段值。
步骤1:首先,您需要在SQL内部创建一个数据库表,并将其命名为“ employee”,并在其中包含以下字段。
步骤2:在Eclipse中创建一个名为“ BatchProcessing”的类。
第三步:按照给定的代码,
package logicProgramming;//您的包裹名称 import java.io.DataInputStream;//读取输入 import java.sql.Connection;//与数据库mysql连接 import java.sql.DriverManager;//从指定的URL获取连接 import java.sql.PreparedStatement;//执行查询 public class BatchProcessing { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); //加载类 Connection cn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/Employee","root", "123"); //establishing the connection with the specified schema in database (here,Employee is schema name root & 123 are user & password) PreparedStatement smt=cn.prepareStatement("insert into employee values(?,?,?,?)"); //准备参数化查询,稍后将执行 DataInputStream kb=new DataInputStream(System.in); String ans=null; //该循环将继续,直到用户拒绝记录插入 do { System.out.println("Enter Employee Id :"); smt.setString(1,kb.readLine()); System.out.println("Enter Employee Name :"); smt.setString(2,kb.readLine()); System.out.println("Enter Employee position :"); smt.setString(3,kb.readLine()); System.out.println("Enter Employee Salary :"); smt.setInt(4,Integer.parseInt(kb.readLine())); System.out.println("Do You Want to Add More Record..\n1.Yes\n2.No"); ans=kb.readLine(); smt.addBatch();//将记录一个接一个地添加到} while(ans.equalsIgnoreCase(“ Yes”)|| ans.equalsIgnoreCase(“ 1”));"Yes")||ans.equalsIgnoreCase("1")); //询问用户是否要添加更多记录 int i[]= smt.executeBatch(); //这将执行我们的批处理 if(i!=null) { System.out.println("Batches Of Record Inserted Successfully........"); } else { System.out.println("Batches Of Record Failed To Insert........"); } } } catch(Exception e) { //这将引发任何消息错误 System.out.println(e.getMessage());} } } }
步骤4:运行您的代码,您将看到如下所示: