欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在Java的JDBC使用中设置事务回滚的保存点的方法

程序员文章站 2024-03-08 18:26:17
新的jdbc3.0保存点的接口提供了额外的事务控制。他们的环境中,如oracle的pl/ sql中的大多数现代的dbms支持保存点。 当设置一个保存点在事务中定义一个逻辑...

新的jdbc3.0保存点的接口提供了额外的事务控制。他们的环境中,如oracle的pl/ sql中的大多数现代的dbms支持保存点。

当设置一个保存点在事务中定义一个逻辑回滚点。如果发生错误,过去一个保存点,则可以使用rollback方法来撤消要么所有的改变或仅保存点之后所做的更改。

connection对象有两个新的方法,可帮助管理保存点:

setsavepoint(string savepointname): 定义了一个新的保存点。它也返回一个savepoint 对象。

releasesavepoint(savepoint savepointname): 删除一个保存点。请注意,它需要一个savepoint 对象作为参数。这个对象通常是由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和事务教程描述回滚的例子。

基于对环境和数据库安装在前面的章节中做此示例代码已经解释。

复制下面的例子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

现在让我们来编译上面的例子如下:

c:>javac jdbcexample.java

当运行jdbcexample,它会产生以下结果:

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!