天天看點

mysql用事務删除sql執行_mySql事務_ _Java中怎樣實作批量删除操作(Java對資料庫進行事務處理)?...

本文是記錄Java中實作批量删除操作(Java對資料庫進行事務處理),在開始之前先來看下面這樣的一個頁面圖:

上面這張圖檔顯示的是從資料庫中查詢出的出租資訊,資訊中進行了分頁處理,然後每行的前面提供了一個複選按鈕和對應的一個删除操作,可以選中多個進行操作,這裡主要是進行删除操作。在執行删除操作之前先要選中對應的行資訊,點選删除選中按鈕進行删除。當進行多條資訊删除的時候,需要使用java的事務處理機制對資料庫進行删除,也就是說删除的時候如果選中的要删除的說有資訊其中一條沒有成功删除的話,那麼就都不删除。

現在是在java中對資料庫實作這一操作,我們可看下面的代碼,它實作了對資料庫的批量删除操作,代碼如下:

[java]  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] 

public boolean updateBatchDel(String sql,String[] param){

boolean flag = false;

getConnection();

try {

con.setAutoCommit(false);

pstmt = con.prepareStatement(sql);

for(int i =0 ;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;

}

(責任編輯:幽靈學院)