在Java的JDBC使用中设置事务回滚的保存点的方法
新的JDBC3.0保存点的接口提供了额外的事务控制。他们的环境中,如Oracle的PL/SQL中的大多数现代的DBMS支持保存点。
当设置一个保存点在事务中定义一个逻辑回滚点。如果发生错误,过去一个保存点,则可以使用rollback方法来撤消要么所有的改变或仅保存点之后所做的更改。
Connection对象有两个新的方法,可帮助管理保存点:
setSavepoint(StringsavepointName):定义了一个新的保存点。它也返回一个Savepoint对象。
releaseSavepoint(SavepointsavepointName):删除一个保存点。请注意,它需要一个Savepoint对象作为参数。这个对象通常是由setSavepoint()方法生成一个保存点。
有一个rollback(StringsavepointName)方法回滚工作到指定的保存点。
下面的例子演示如何使用Savepoint对象:
try{ //Assumeavalidconnectionobjectconn conn.setAutoCommit(false); Statementstmt=conn.createStatement(); //setaSavepoint Savepointsavepoint1=conn.setSavepoint("Savepoint1"); StringSQL="INSERTINTOEmployees"+ "VALUES(106,20,'Rita','Tez')"; stmt.executeUpdate(SQL); //SubmitamalformedSQLstatementthatbreaks StringSQL="INSERTEDINEmployees"+ "VALUES(107,22,'Sita','Tez')"; stmt.executeUpdate(SQL); //Ifthereisnoerror,committhechanges. conn.commit(); }catch(SQLExceptionse){ //Ifthereisanyerror. conn.rollback(savepoint1); }
在这种情况下没有上述INSERT语句会成功,一切都将被回滚。
下面是利用setSavepoint和事务教程描述回滚的例子。
基于对环境和数据库安装在前面的章节中做此示例代码已经解释。
复制下面的例子JDBCExample.java,编译并运行,如下所示:
//STEP1.Importrequiredpackages importjava.sql.*; publicclassJDBCExample{ //JDBCdrivernameanddatabaseURL staticfinalStringJDBC_DRIVER="com.mysql.jdbc.Driver"; staticfinalStringDB_URL="jdbc:mysql://localhost/EMP"; //Databasecredentials staticfinalStringUSER="username"; staticfinalStringPASS="password"; publicstaticvoidmain(String[]args){ Connectionconn=null; Statementstmt=null; try{ //STEP2:RegisterJDBCdriver Class.forName("com.mysql.jdbc.Driver"); //STEP3:Openaconnection System.out.println("Connectingtodatabase..."); conn=DriverManager.getConnection(DB_URL,USER,PASS); //STEP4:Setautocommitasfalse. conn.setAutoCommit(false); //STEP5:Executeaquerytodeletestatmentwith //requiredargumentsforRSexample. System.out.println("Creatingstatement..."); stmt=conn.createStatement(); //STEP6:Nowlistalltheavailablerecords. Stringsql="SELECTid,first,last,ageFROMEmployees"; ResultSetrs=stmt.executeQuery(sql); System.out.println("Listresultsetforreference...."); printRs(rs); //STEP7:deleterowshavingIDgraterthan104 //Butsavepointbeforedoingso. Savepointsavepoint1=conn.setSavepoint("ROWS_DELETED_1"); System.out.println("Deletingrow...."); StringSQL="DELETEFROMEmployees"+ "WHEREID=110"; stmt.executeUpdate(SQL); //oops...wedeletedtoowrongemployees! //STEP8:Rollbackthechangesafetrsavepoint2. conn.rollback(savepoint1); //STEP9:deleterowshavingIDgraterthan104 //Butsavepointbeforedoingso. Savepointsavepoint2=conn.setSavepoint("ROWS_DELETED_2"); System.out.println("Deletingrow...."); SQL="DELETEFROMEmployees"+ "WHEREID=95"; stmt.executeUpdate(SQL); //STEP10:Nowlistalltheavailablerecords. sql="SELECTid,first,last,ageFROMEmployees"; rs=stmt.executeQuery(sql); System.out.println("Listresultsetforreference...."); printRs(rs); //STEP10:Clean-upenvironment rs.close(); stmt.close(); conn.close(); }catch(SQLExceptionse){ //HandleerrorsforJDBC se.printStackTrace(); //Ifthereisanerrorthenrollbackthechanges. System.out.println("Rollingbackdatahere...."); try{ if(conn!=null) conn.rollback(); }catch(SQLExceptionse2){ se2.printStackTrace(); }//endtry }catch(Exceptione){ //HandleerrorsforClass.forName e.printStackTrace(); }finally{ //finallyblockusedtocloseresources try{ if(stmt!=null) stmt.close(); }catch(SQLExceptionse2){ }//nothingwecando try{ if(conn!=null) conn.close(); }catch(SQLExceptionse){ se.printStackTrace(); }//endfinallytry }//endtry System.out.println("Goodbye!"); }//endmain publicstaticvoidprintRs(ResultSetrs)throwsSQLException{ //Ensurewestartwithfirstrow rs.beforeFirst(); while(rs.next()){ //Retrievebycolumnname intid=rs.getInt("id"); intage=rs.getInt("age"); Stringfirst=rs.getString("first"); Stringlast=rs.getString("last"); //Displayvalues System.out.print("ID:"+id); System.out.print(",Age:"+age); System.out.print(",First:"+first); System.out.println(",Last:"+last); } System.out.println(); }//endprintRs() }//endJDBCExample
现在让我们来编译上面的例子如下:
C:>javacJDBCExample.java
当运行JDBCExample,它会产生以下结果:
C:>javaJDBCExample
Connectingtodatabase... Creatingstatement... Listresultsetforreference.... 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 Deletingrow.... Deletingrow.... Listresultsetforreference.... 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!