在Java的JDBC使用中設(shè)置事務(wù)回滾的保存點的方法
新的JDBC3.0保存點的接口提供了額外的事務(wù)控制。他們的環(huán)境中,如Oracle的PL/ SQL中的大多數(shù)現(xiàn)代的DBMS支持保存點。
當(dāng)設(shè)置一個保存點在事務(wù)中定義一個邏輯回滾點。如果發(fā)生錯誤,過去一個保存點,則可以使用rollback方法來撤消要么所有的改變或僅保存點之后所做的更改。
Connection對象有兩個新的方法,可幫助管理保存點:
setSavepoint(String savepointName): 定義了一個新的保存點。它也返回一個Savepoint 對象。
releaseSavepoint(Savepoint savepointName): 刪除一個保存點。請注意,它需要一個Savepoint 對象作為參數(shù)。這個對象通常是由setSavepoint()方法生成一個保存點。
有一個rollback ( String savepointName ) 方法回滾工作到指定的保存點。
下面的例子演示如何使用Savepoint對象:
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
//set a Savepoint
Savepoint savepoint1 = conn.setSavepoint("Savepoint1");
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Tez')";
stmt.executeUpdate(SQL);
// If there is no error, commit the changes.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback(savepoint1);
}
在這種情況下沒有上述INSERT語句會成功,一切都將被回滾。
下面是利用setSavepoint和事務(wù)教程描述回滾的例子。
基于對環(huán)境和數(shù)據(jù)庫安裝在前面的章節(jié)中做此示例代碼已經(jīng)解釋。
復(fù)制下面的例子JDBCExample.java,編譯并運行,如下所示:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Set auto commit as false.
conn.setAutoCommit(false);
//STEP 5: Execute a query to delete statment with
// required arguments for RS example.
System.out.println("Creating statement...");
stmt = conn.createStatement();
//STEP 6: Now list all the available records.
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("List result set for reference....");
printRs(rs);
// STEP 7: delete rows having ID grater than 104
// But save point before doing so.
Savepoint savepoint1 = conn.setSavepoint("ROWS_DELETED_1");
System.out.println("Deleting row....");
String SQL = "DELETE FROM Employees " +
"WHERE ID = 110";
stmt.executeUpdate(SQL);
// oops... we deleted too wrong employees!
//STEP 8: Rollback the changes afetr save point 2.
conn.rollback(savepoint1);
// STEP 9: delete rows having ID grater than 104
// But save point before doing so.
Savepoint savepoint2 = conn.setSavepoint("ROWS_DELETED_2");
System.out.println("Deleting row....");
SQL = "DELETE FROM Employees " +
"WHERE ID = 95";
stmt.executeUpdate(SQL);
//STEP 10: Now list all the available records.
sql = "SELECT id, first, last, age FROM Employees";
rs = stmt.executeQuery(sql);
System.out.println("List result set for reference....");
printRs(rs);
//STEP 10: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
// If there is an error then rollback the changes.
System.out.println("Rolling back data here....");
try{
if(conn!=null)
conn.rollback();
}catch(SQLException se2){
se2.printStackTrace();
}//end try
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
public static void printRs(ResultSet rs) throws SQLException{
//Ensure we start with first row
rs.beforeFirst();
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
System.out.println();
}//end printRs()
}//end JDBCExample
現(xiàn)在讓我們來編譯上面的例子如下:
C:>javac JDBCExample.java
當(dāng)運行JDBCExample,它會產(chǎn)生以下結(jié)果:
C:>java JDBCExample
Connecting to database... Creating statement... List result set for reference.... ID: 95, Age: 20, First: Sima, Last: Chug ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 30, First: Sumit, Last: Mittal ID: 110, Age: 20, First: Sima, Last: Chug Deleting row.... Deleting row.... List result set for reference.... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 30, First: Sumit, Last: Mittal ID: 110, Age: 20, First: Sima, Last: Chug Goodbye!
相關(guān)文章
mybatisplus 的SQL攔截器實現(xiàn)關(guān)聯(lián)查詢功能
大家都知道m(xù)ybatisplus不支持關(guān)聯(lián)查詢,后來學(xué)習(xí)研究發(fā)現(xiàn)mybatisplus的SQL攔截器可以實現(xiàn)這一操作,下面小編給大家分享我的demo實現(xiàn)基本的關(guān)聯(lián)查詢功能沒有問題,對mybatisplus關(guān)聯(lián)查詢相關(guān)知識感興趣的朋友一起看看吧2021-06-06
spring?boot對敏感信息進行加解密的項目實現(xiàn)
本文主要介紹了spring?boot對敏感信息進行加解密的項目實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
Java注解中@Component和@Bean的區(qū)別
這篇文章主要介紹了@Component和@Bean的區(qū)別,在這給大家簡單介紹下作用對象不同:@Component 注解作用于類,而 @Bean 注解作用于方法,具體實例代碼參考下本文2024-03-03
通過反射注解批量插入數(shù)據(jù)到DB的實現(xiàn)方法
今天小編就為大家分享一篇關(guān)于通過反射注解批量插入數(shù)據(jù)到DB的實現(xiàn)方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
詳解mybatis.generator配上最新的mysql 8.0.11的一些坑
這篇文章主要介紹了詳解mybatis.generator配上最新的mysql 8.0.11的一些坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
IDEA類與方法注釋模板設(shè)置圖文教程(非常詳細(xì))
IDEA自帶的注釋模板不是太好用,我本人到網(wǎng)上搜集了很多資料系統(tǒng)的整理了一下制作了一份比較完整的模板來分享給大家,下面這篇文章主要給大家介紹了關(guān)于IDEA類與方法注釋模板設(shè)置的相關(guān)資料,需要的朋友可以參考下2022-09-09

