What are save points in JDBC? Explain?

JDBCJava 8MySQLMySQLi Database

Savepoint interface gives you the additional transactional control. Most modern DBMS, support save points within their environments such as Oracle's PL/SQL.

When you set a save point you define a logical rollback point within a transaction. If an error occurs past a save point, you can use the rollback method to undo either all the changes or only the changes made after the save point.

The Connection object has two new methods that help you manage save points −

  • setSavepoint(String savepointName): Defines a new save point. It also returns a Savepoint object.

  • releaseSavepoint(Savepoint savepointName): Deletes a Savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a save point generated by the setSavepoint() method.

There is one rollback (String savepointName) method, which rolls back work to the specified save point.

Example

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);
}
raja
Published on 20-Mar-2019 17:07:40
Advertisements