How to Create a Savepoint in JDBC?
A Savepoint object is used to save the current state of the database which can be rolled-back afterwards to that state of the database. Savepoints are similar to the SQL Transactions and are generally to rollback if something goes wrong within the current transaction. The connection.setSavepoint() method of Connection interface in Java is used to create an object which references a current state of the database within the transaction. The following example shows the usage of Savepoint and Rollback in JDBC application.
syntax
connection.setSavepoint()
Returns: It returns a new Savepoint object.
Exceptions: SQLException is thrown if a database access error occurs, this method is called while participating in a distributed transaction, this method is called on a closed connection or this Connection object is currently in auto-commit mode. SQLFeatureNotSupportedException is thrown if the JDBC driver does not support this method.
Example
Java
import java.io.*;
import java.sql.*;
class GFG {
public static void main(String[] args)
{
String jdbcEndpoint
String userid = "GFG" ;
String password = "GEEKSFORGEEKS" ;
Connection connection = DriverManager.getConnection(
jdbcEndpoint, userid, password);
Statement deleteStmt = connection.createStatement();
String deleteQuery
= "DELETE FROM USER WHERE AGE > 15" ;
connection.setAutoCommit( false );
Savepoint beforeDeleteSavepoint
= connection.setSavepoint();
ResultSet res
= deleteStmt.executeQuery(deleteQuery);
connection.rollback(beforeDeleteSavepoint);
connection.commit();
}
}
|
Last Updated :
28 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...