📜  如何在 JDBC 中创建保存点?

📅  最后修改于: 2022-05-13 01:54:35.931000             🧑  作者: Mango

如何在 JDBC 中创建保存点?

Savepoint对象用于保存数据库的当前状态,然后可以将其回滚到数据库的该状态。保存点类似于 SQL 事务,并且通常在当前事务中出现问题时回滚。 Java Connection 接口的connection.setSavepoint()方法用于创建一个对象,该对象引用事务中数据库的当前状态。下面的例子展示了 JDBC 应用中 Savepoint 和 Rollback 的用法。

句法

connection.setSavepoint()

返回:它返回一个新的Savepoint对象。

异常:如果发生数据库访问错误,在参与分布式事务时调用此方法,在关闭的连接上调用此方法或此 Connection 对象当前处于自动提交模式,则抛出 SQLException 。如果 JDBC 驱动程序不支持此方法,则抛出SQLFeatureNotSupportedException

例子

Java
// Java program to demonstrate how to make a save point
  
import java.io.*;
import java.sql.*;
  
class GFG {
    public static void main(String[] args)
    {
        // db credentials
        String jdbcEndpoint
            = "jdbc:mysql://localhost:3000/GEEKSFORGEEKS";
        String userid = "GFG";
        String password = "GEEKSFORGEEKS";
  
        // create a connection to db
        Connection connection = DriverManager.getConnection(
            jdbcEndpoint, userid, password);
  
        // construct a query
        Statement deleteStmt = connection.createStatement();
        String deleteQuery
            = "DELETE FROM USER WHERE AGE > 15";
  
        // Disable auto commit to connection
        connection.setAutoCommit(false);
  
        /*    Table USER
       +--------+---------+------------+
       | USR_ID | NAME    | AGE        |
       +--------+---------+------------+
       |      1 | GFG_1      | 10           |
       |      2 | GFG_2   | 20         |
       |      3 | GFG_3   | 25           |
       +--------+---------+------------+
       */
  
        // Create a savepoint object before executing the
        // deleteQuery
        Savepoint beforeDeleteSavepoint
            = connection.setSavepoint();
  
        // Executing the deleteQuery
        ResultSet res
            = deleteStmt.executeQuery(deleteQuery);
  
        /*    Table USER after executing deleteQuery
       +--------+---------+------------+
       | USR_ID | NAME    | AGE        |
       +--------+---------+------------+
       |      1 | GFG_1      | 10           |
       +--------+---------+------------+
       */
  
        // Rollback to our beforeDeleteSavepoint
        connection.rollback(beforeDeleteSavepoint);
        connection.commit();
  
        /*    Table USER after rollback
        +--------+---------+------------+
        | USR_ID | NAME    | AGE        |
        +--------+---------+------------+
        |      1 | GFG_1   | 10            |
        |      2 | GFG_2   | 20          |
        |      3 | GFG_3   | 25            |
        +--------+---------+------------+
        */
    }
}



表中的保存点