
There are some situations when you have to only rollback() to some specific statement and not all statements in a transaction. This can be achieved by introducing some labels to the statements in the transactions. These labels are known as savepoints. The JDBC 3.0 API adds the method Connection.setSavepoint, which sets a savepoint within the current transaction. The Connection.rollback method has been overloaded to take a savepoint argument.
The following example will demonstrate how do we use savepoints to handle the transactions more effectively.
Note:- The program will not change any data as the commit() is called after rollback().
package com.visualbuilder;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Savepoint; import java.sql.Statement;
public class SavepointExample { public static void main(String[] args) { try { /** Loading the driver*/ Class.forName("com.mysql.jdbc.Driver"); /** Getting Connection*/ Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); /** Creating Statement*/ con.setAutoCommit(false); Statement stmt= con.createStatement(); stmt.execute("insert into visualbuilder (id,name)values(10,'test')"); // set savepoint Savepoint savepoint1 = con.setSavepoint("SAVEPOINT_1"); stmt.execute("delete from visualbuilder"); System.out.println("rollback to savepoint called "); con.rollback(savepoint1); con.commit(); con.close(); } catch (Exception e){ e.printStackTrace(); } } } Output:- rollback to savepoint called. | |
Java Discussion
- - Interviewing Next week -
- - Sudoku solver
- - Setting tab order in swin
- - Java opportunities
- - Struts


