本文是記錄Java中實現批量刪除操作(Java對數據庫進行事務處理),在開始之前先來看下面這樣的一個頁面圖:
上面這張圖片顯示的是從數據庫中查詢出的出租信息,信息中進行了分頁處理,然后每行的前面提供了一個復選按鈕和對應的一個刪除操作,可以選中多個進行操作,這里主要是進行刪除操作。在執行刪除操作之前先要選中對應的行信息,點擊刪除選中按鈕進行刪除。當進行多條信息刪除的時候,需要使用java的事務處理機制對數據庫進行刪除,也就是說刪除的時候如果選中的要刪除的說有信息其中一條沒有成功刪除的話,那么就都不刪除。
現在是在java中對數據庫實現這一操作,我們可看下面的代碼,它實現了對數據庫的批量刪除操作,代碼如下:
[java] <SPAN style="WHITE-SPACE: pre"> </SPAN>public Connection con=null;
public PreparedStatement pstmt=null;
/**
* 得到連接對象
*/
public void getConnection(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/zufang?user=root&password=root&useUnicode=true&characterEncoding=GB2312";
try {
Class.forName(driver);
con=DriverManager.getConnection(url,"root","root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection con=null;
public PreparedStatement pstmt=null;
/**
* 得到連接對象
*/
public void getConnection(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/zufang?user=root&password=root&useUnicode=true&characterEncoding=GB2312";
try {
Class.forName(driver);
con=DriverManager.getConnection(url,"root","root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
[java] <SPAN style="WHITE-SPACE: pre"> </SPAN>/**
* 批量刪除信息表中的信息
* @param sql
* @param param
* @return
*/
public boolean updateBatchDel(String sql,String[] param){
boolean flag = false;
getConnection();
try {
con.setAutoCommit(false);
pstmt = con.prepareStatement(sql);
for(int i =0 ;i<param.length;i++){
pstmt.setString(1,param[i].trim());
pstmt.addBatch();
}
pstmt.executeBatch(); //批量執行
con.commit();//提交事務
flag = true;
} catch (SQLException e) {
try {
con.rollback(); //進行事務回滾
} catch (SQLException ex) {
ex.printStackTrace();
}
}finally {
closeAll(null,pstmt,con);
}
return flag;
}
(責任編輯:幽靈學院)