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

详解Java的JDBC API中事务的提交和回滚

程序员文章站 2024-03-07 22:47:21
如果jdbc连接是在自动提交模式下,它在默认情况下,那么每个sql语句都是在其完成时提交到数据库。 这可能是对简单的应用程序,但有三个原因,你可能想关闭自动提交和管理自己...

如果jdbc连接是在自动提交模式下,它在默认情况下,那么每个sql语句都是在其完成时提交到数据库。

这可能是对简单的应用程序,但有三个原因,你可能想关闭自动提交和管理自己的事务:

  1. 为了提高性能
  2. 为了保持业务流程的完整性
  3. 使用分布式事务

若要控制事务,以及何时更改应用到数据库。它把单个sql语句或一组sql语句作为一个逻辑单元,而且如果任何语句失败,整个事务失败。

若要启用,而不是jdbc驱动程序默认使用auto-commit模式手动事务支持,使用connection对象的的setautocommit()方法。如果传递一个布尔值false到setautocommit(),关闭自动提交。可以传递一个布尔值true将其重新打开。

例如,如果有一个名为conn connection对象,以下代码来关闭自动提交:

conn.setautocommit(false);

提交和回滚
一旦已经完成了变化,要提交更改,然后调用commit(在连接对象)方法,如下所示:

conn.commit( );

否则回滚更新对数据库所做的使用命名连接conn,使用下面的代码:

conn.rollback( );

下面的例子演示了如何使用一个提交和回滚对象:

try{
  //assume a valid connection object conn
  conn.setautocommit(false);
  statement stmt = conn.createstatement();
  
  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', 'singh')";
  stmt.executeupdate(sql);
  // if there is no error.
  conn.commit();
}catch(sqlexception se){
  // if there is any error.
  conn.rollback();
}

在这种情况下没有上述insert语句会成功,一切都将被回滚。

事务提交和回滚示例
以下是使用事务提交和回滚描述的例子。

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

复制过去下面的例子中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 create statment with
   // required arguments for rs example.
   system.out.println("creating statement...");
   stmt = conn.createstatement(
              resultset.type_scroll_insensitive,
              resultset.concur_updatable);
   
   //step 6: insert a row into employees table
   system.out.println("inserting one row....");
   string sql = "insert into employees " +
          "values (106, 20, 'rita', 'tez')";
   stmt.executeupdate(sql); 

   //step 7: insert one more row into employees table
   sql = "insert into employees " +
          "values (107, 22, 'sita', 'singh')";
   stmt.executeupdate(sql);

   //step 8: commit data here.
   system.out.println("commiting data here....");
   conn.commit();
  
  //step 9: 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 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...
inserting one row....
commiting data here....
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: 28, first: sumit, last: mittal
id: 106, age: 20, first: rita, last: tez
id: 107, age: 22, first: sita, last: singh
goodbye!