Mega Code Archive

 
Categories / Java Tutorial / Database
 

Rollback to savepoint

import java.sql.Connection; import java.sql.DriverManager; import java.sql.Savepoint; import java.sql.Statement; public class Main {   public static void main(String[] args) throws Exception {     Connection conn = getConnection();     conn.setAutoCommit(false);     Statement st = conn.createStatement();     st.executeUpdate("create table survey (id int,myURL CHAR);");     st.executeUpdate("insert into survey(id) values(01)");     st.executeUpdate("insert into survey(id) values(02)");     Savepoint mySavepoint = conn.setSavepoint("MYSAVEPOINT");     st.executeUpdate("insert into survey(id) values(03)");     conn.commit();          conn.rollback (mySavepoint);          st.close();     conn.close();   }   private static Connection getConnection() throws Exception {     Class.forName("org.hsqldb.jdbcDriver");     String url = "jdbc:hsqldb:mem:data/tutorial";     return DriverManager.getConnection(url, "sa", "");   } } Connection.releaseSavepoint() is used for removing a savepoint from a transaction. A rollback implicitly releases any savepoints that were defined after it. Once a transaction is committed or completely rolled back, all defined savepoints are released. Once a savepoint has been removed, any reference to it will cause a SQLException to be thrown. It is also possible to nest savepoints within transactions.