?? sqltransaction.java
字號:
package ch03.section07;
import java.sql.*;
public class SQLTransaction {
public Connection conn = null;
public Statement stmt = null;
ResultSet set = null;
// 構造方法初始化數據庫連接,并將AutoCommit設定為False
public SQLTransaction(Connection con) throws SQLException {
this.conn = con;
conn.setAutoCommit(false);
this.stmt = con.createStatement();
}
public void executeUpdate(String sql) throws SQLException {
//如果更新操作失敗,回滾到事務起點并拋出異常
try {
stmt.executeUpdate(sql);
}
catch (SQLException e) {
rollbackTransaction();
throw e;
}
}
public ResultSet executeQuery(String sql) throws SQLException {
// 獲得結果集。
try {
set = stmt.executeQuery(sql);
}
catch (SQLException e) {
throw e;
}
finally {
return set;
}
}
public void commitTransaction() throws SQLException {
// 事務結束,提交更新
try {
conn.commit();
// 如果發生異常,回滾到事務起點
}
catch (Exception e) {
rollbackTransaction();
throw new SQLException("無法提交當前事務");
}
}
public void rollbackTransaction() throws SQLException {
// 回滾到事務起點
try {
conn.rollback();
conn.setAutoCommit(true);
// 如果在回滾過程中發生異常,忽略該異常
}
catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
public void close() throws SQLException {
// 關閉連接
try {
if (set != null) {
set.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -