批處理是一次性向數據庫發出多條查詢指令,一起執行
Statement 接口定義的方法:
|—增加批處理語句:
public void addBatch(String sql)
|—執行批處理:
public int [] executeBatch()throws SQLException
PreparedStatement接口定義的方法:
增加批處理:public void addBatche()throws SQLexceeption
范例:
public class TestConn {
static final String DBDRIVER="oracle.jdbc.driver.OracleDriver";
static final String url="jdbc:oracle:thin:@localhost:1521:ORCL";
private static final String USER="***";
private static final String PASSWORD="***";
public static void main(String[] args) throws Exception {
Class .forName(DBDRIVER);
Connection conn=DriverManager.getConnection(url,USER,PASSWORD);
Statement stmt=conn.createStatement();
conn.setAutoCommit(false);
try{//增加數據
stmt.addBatch("Insert into myemp(ename,job)values('sdvb1','測試ad')");
stmt.addBatch("Insert into myemp(ename,job)values('sdvb2','測試ad')");
stmt.addBatch("Insert into myemp(ename,job)values('sdvb3','測試ad')");
stmt.addBatch("Insert into myemp(ename,job)values('sdvb4','測試ad')");
int result[]=stmt.executeBatch();
System.out.println(Arrays.toString(result));
conn.commit();//沒有錯誤,提交數據
}catch(Exception e){
e.printStackTrace();
conn.rollback();//有錯誤,回滾數據
}
conn.close();
}
}