JDBC - 提交和回滚示例



以下是示例,它使用了commitrollback,这些在事务教程中进行了描述。

此示例代码是根据前面章节中完成的环境和数据库设置编写的。

使用 Commit 语句将插入的行持久化到表中的示例

在这个例子中,我们有六个静态字符串,包含数据库连接 URL、用户名、密码、SELECT 查询和两个 INSERT 查询。插入查询用于在 Employees 表中插入两条记录,而 Select 查询将用于获取所有员工。现在,使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。使用 setAutoCommit(false),我们将自动提交设置为 false,默认情况下为 true。连接准备就绪后,我们使用 connection.createStatement() 方法创建了一个 Statement 对象。在创建 Statement 对象时,我们使用 ResultSet 类型为 TYPE_SCROLL_INSENSITIVE 和 CONCUR_READ_ONLY。然后使用 statement.executeUpdate() 执行 INSERT 查询。现在,使用 commit() 方法,更改将持久化到数据库。

我们定义了一个 printResultSet() 方法,它以结果集作为参数,迭代它并打印结果集的所有记录。所有更改提交后,将调用 printResultSet() 方法以打印所有记录,以验证插入的记录是否可用。

将以下示例复制并粘贴到 JDBCCommitTransactionExample.java 中,编译并运行如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCCommitTransactionExample {
   static final String DB_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "SELECT id, first, last, age FROM Employees";
   static final String INSERT_QUERY = "INSERT INTO Employees (first, last, age) values('Rita', 'Tez', 20)";
   static final String INSERT_QUERY_2 = "INSERT INTO Employees (first, last, age) values('Sita', 'Singh', 20)";

   public static void printResultSet(ResultSet rs) throws SQLException{
      // Ensure we start with first row
      rs.beforeFirst();
      while(rs.next()){
         // Display values
         System.out.print("ID: " + rs.getInt("id"));
         System.out.print(", Age: " + rs.getInt("age"));
         System.out.print(", First: " + rs.getString("first"));
         System.out.println(", Last: " + rs.getString("last"));
      }
      System.out.println();
   }

   public static void main(String[] args) {

      Connection conn = null;
      Statement stmt = null;
      try{
         // Open a connection
         System.out.println("Connecting to database...");
         conn = DriverManager.getConnection(DB_URL,USER,PASS);

         // Set auto commit as false.
         conn.setAutoCommit(false);

         // 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);

         // INSERT a row into Employees table
         System.out.println("Inserting one row....");
         stmt.executeUpdate(INSERT_QUERY);  

         // INSERT one more row into Employees table
         System.out.println("Inserting another row....");
         stmt.executeUpdate(INSERT_QUERY_2);

         // Commit data here.
         System.out.println("Commiting data here....");
         conn.commit();

         // Now list all the available records.
         ResultSet rs = stmt.executeQuery(QUERY);
         System.out.println("List result set for reference....");
         printResultSet(rs);

         // Clean-up environment
         rs.close();
         stmt.close();
         conn.close();
      }catch(SQLException se){
         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();
            }
         }catch(Exception e){
            e.printStackTrace();
         }finally{
            // finally block used to close resources
         try{
            if(stmt!=null)
               stmt.close();
         }catch(SQLException se2){
            se2.printStackTrace();
         } 
            try{
               if(conn!=null)
                  conn.close();
            }catch(SQLException se){
               se.printStackTrace();
         }
      }		   
   }
}

输出

现在让我们编译上述示例,如下所示:

C:\>javac JDBCCommitTransactionExample.java
C:\>

当您运行JDBCCommitTransactionExample时,它会产生以下结果:

C:\>java JDBCCommitTransactionExample
Connecting to database...
Creating statement...
Inserting one row....
Inserting another row....
Commiting data here....
List result set for reference....
ID: 1, Age: 23, First: Zara, Last: Ali
ID: 2, Age: 30, First: Mahnaz, Last: Fatma
ID: 3, Age: 35, First: Zaid, Last: Khan
ID: 4, Age: 33, First: Sumit, Last: Mittal
ID: 5, Age: 40, First: John, Last: Paul
ID: 6, Age: 20, First: Rita, Last: Tez
ID: 7, Age: 20, First: Sita, Last: Singh
C:\>

使用 Rollback 语句还原表中插入行的示例

在这个例子中,我们有六个静态字符串,包含数据库连接 URL、用户名、密码、SELECT 查询和两个 INSERT 查询。插入查询用于在 Employees 表中插入两条记录,而 Select 查询将用于获取所有员工。其中一个插入查询无效,因为 Employee1 表不存在。现在,使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。使用 setAutoCommit(false),我们将自动提交设置为 false,默认情况下为 true。连接准备就绪后,我们使用 connection.createStatement() 方法创建了一个 Statement 对象。在创建 Statement 对象时,我们使用 ResultSet 类型为 TYPE_SCROLL_INSENSITIVE 和 CONCUR_READ_ONLY。然后使用 statement.executeUpdate() 执行 INSERT 查询。

由于第二个 INSERT 查询无效,因此将引发 SQLException。我们处理了异常,并使用 rollback() 方法还原更改。

我们定义了一个 printResultSet() 方法,它以结果集作为参数,迭代它并打印结果集的所有记录。所有更改提交后,将调用 printResultSet() 方法以打印所有记录,以验证插入的记录是否已还原。

将以下示例复制并粘贴到 JDBCRollbackTransactionExample.java 中,编译并运行如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCRollbackTransactionExample {
   static final String MYSQL_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT";
   static final String USER_NAME = "guest";
   static final String PASSWORD = "guest123";
   static final String INSERT_QUERY1 = "INSERT INTO Employees (first, last, age) values('Jeevan', 'Rao', 35)";
   static final String INSERT_QUERY2 = "INSERT INTO Employees11 (first, last, age) values('Aditya', 'Chaube', 40)";
   static final String SELECT_QUERY = "SELECT id, age, first, last FROM Employees";

   public static void printResultSet(ResultSet rs) throws SQLException{
      // Ensure we start with first row
      rs.beforeFirst();
      while(rs.next()){
         // Display values
         System.out.print("ID: " + rs.getInt("id"));
         System.out.print(", Age: " + rs.getInt("age"));
         System.out.print(", First: " + rs.getString("first"));
         System.out.println(", Last: " + rs.getString("last"));
      }
      System.out.println();
   }

   public static void main(String[] args) {
      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;
      try{
         // Open database connection
         conn = DriverManager.getConnection(MYSQL_URL,USER_NAME,PASSWORD);
         System.out.println(" Connection established with TUTORIALSPOINT database.");

         conn.setAutoCommit(false);
         stmt = conn.createStatement(
            ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_UPDATABLE);

         System.out.println("Before inserting a row into Employees table");
         stmt.executeUpdate(INSERT_QUERY1);  
         System.out.println("Inserted a row into Employees table");
         stmt.executeUpdate(INSERT_QUERY2);

         System.out.println("Before committing 2 inserts.");
         conn.commit();
         System.out.println(" After committing 2 inserts.");

         rs = stmt.executeQuery(SELECT_QUERY);
         System.out.println("List ALL records of Employees table..");

         printResultSet(rs);

         // Clean-up resources
         rs.close();
         stmt.close();
         conn.close();
      }catch(SQLException se){
         se.printStackTrace();
         System.out.println("If error has occured, discard changes");
         try{
            if(conn!=null)
               conn.rollback();
               //Checking if records are in 'before-insert' state. 
               rs = stmt.executeQuery(SELECT_QUERY);
               System.out.println("List ALL records of Employees table..");
               printResultSet(rs);
               // Clean-up resources
               rs.close();
               stmt.close();
               conn.close();
         }catch(SQLException se){      
            se.printStackTrace();
            System.out.println("If error has occured, discard changes");
            try{
               if(conn!=null)
                  conn.rollback();

               // Checking if records are in 'before-insert' state. 
               rs = stmt.executeQuery(SELECT_QUERY);
               System.out.println("List ALL records of Employees table..");

               printResultSet(rs);
            }
            catch(SQLException se2){
               se2.printStackTrace();
            }catch(Exception e){
               e.printStackTrace();
            }finally{
               try{
                  if(rs != null){
                     rs.close();
                  }
               }catch(SQLException se1){
                  se1.printStackTrace();
               }
               try{
                  if(stmt!=null)
                     stmt.close();
               }catch(SQLException se2){
                  se2.printStackTrace();
               } 
               try{
                  if(conn!=null)
                     conn.close();
               }catch(SQLException se){
                  se.printStackTrace();
               }
            }		   
         }
      }
   }
}

输出

现在让我们编译上述示例,如下所示:

C:\>javac JDBCRollbackTransactionExample.java
C:\>

当您运行JDBCRollbackTransactionExample时,它会产生以下结果:

C:\>java JDBCRollbackTransactionExample
Connection established with TUTORIALSPOINT database.
Before inserting a row into Employees table
Inserted a row into Employees table
java.sql.SQLSyntaxErrorException: Table 'tutorialspoint.employees11' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:112)
...	
If error has occured, discard changes
List ALL records of Employees table..
ID: 1, Age: 18, First: Zara, Last: Ali
ID: 2, Age: 25, First: Mahnaz, Last: Fatma
ID: 3, Age: 30, First: Zaid, Last: Khan
ID: 4, Age: 28, First: Sumit, Last: Mittal
ID: 7, Age: 20, First: Rita, Last: Tez
ID: 8, Age: 20, First: Sita, Last: Singh

C:\>
jdbc-transactions.htm
广告