📅  最后修改于: 2020-10-13 01:54:48             🧑  作者: Mango
代替执行单个查询,我们可以执行一批(组)查询。它使性能快速。
java.sql.Statement和java.sql.PreparedStatement接口提供了用于批处理的方法。
快速的表现
批处理所需的方法如下:
Method | Description |
---|---|
void addBatch(String query) | It adds query into batch. |
int[] executeBatch() | It executes the batch of queries. |
让我们看一下jdbc中批处理的简单示例。它遵循以下步骤:
import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into user420 values(190,'abhi',40000)");
stmt.addBatch("insert into user420 values(191,'umesh',50000)");
stmt.executeBatch();//executing the batch
con.commit();
con.close();
}}
如果您看到表user420,则添加了两个记录。
import java.sql.*;
import java.io.*;
class BP{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
System.out.println("enter salary");
String s3=br.readLine();
int salary=Integer.parseInt(s3);
ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.addBatch();
System.out.println("Want to add more records y/n");
String ans=br.readLine();
if(ans.equals("n")){
break;
}
}
ps.executeBatch();
System.out.println("record successfully saved");
con.close();
}catch(Exception e){System.out.println(e);}
}}
它将查询添加到批处理中,直到用户按n。最后,它执行批处理。因此,所有添加的查询将被触发。