批处理的好处:提高了数据的传输效率。
prepareStatement实现批处理:
以下是通过statement实现批处理:
prepareStatement实现批处理:
import java.sql.*;
public class TestPreparedStatement {
public static void main(String[] args){
Connection conn=null;
PreparedStatement pstm=null;
try{
conn=ConnectTool.getConnection();
conn.setAutoCommit(false);
String sql="update emp set sal=10000 where empNo=?";
pstm=conn.prepareStatement(sql);
pstm.setInt(1, 7654);
pstm.addBatch();
pstm.setInt(1, 7782);
pstm.addBatch();
int[] a=pstm.executeBatch();
for(int i:a){
System.out.println(i);
}
conn.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
ConnectTool.releasersc(null, pstm, conn);
}
}
}
以下是通过statement实现批处理:
import java.sql.*;
public class TestBatchTransaction {
public static void main(String args[]){
Connection conn=null;
Statement stm=null;
PreparedStatement pstm=null;
ResultSet rs=null;
try{
conn=ConnectTool.getConnection();
conn.setAutoCommit(false);
String sql="update emp set Ename='cning' where MGR=7902";
String sql1="delete from emp where empno=7369";
stm=conn.createStatement();
stm.addBatch(sql);
stm.addBatch(sql1);
int[]a=stm.executeBatch();
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
conn.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
ConnectTool.releasersc(null, pstm, conn);
}
}
}