English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JDBC setSavepoint, releaseSavepoint example

The following is an example, which usessetSavepointandrollbackIt is described in the transaction tutorial.

This example code is written based on the environment and database settings in the previous chapters.

Copy and paste the following example into JDBCExample.java, as follows compile and run:}

//Step1.Import the required packages
import java.sql.*;
public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP
   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //Step2Register the JDBC driver
      Class.forName("com.mysql.jdbc.Driver");
      //Step3Establish a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      //Step4Set auto-commit to false.
      conn.setAutoCommit(false);
      //Step5Execute the query to delete the statement
      // The necessary parameters for the RS example.
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
	  //Step6:Now list all available records.
      String sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);
      System.out.println("List result set for reference....");
      printRs(rs);
      // Step7Delete ID greater than104line
      // But before doing this, you need to save a point first.
      Savepoint savepoint1 = conn.setSavepoint("ROWS_DELETED_"1");
      System.out.println("Deleting row....");
      String SQL = "DELETE FROM Employees" +
                   "WHERE ID = 110";
      stmt.executeUpdate(SQL);  
      // Oh no... We deleted too many wrong employees!
      //Step8At the savepoint2Roll back the changes after that.
      conn.rollback(savepoint1);
    // Step9Delete ID greater than104line
      // But before doing this, you need to save a point first.
      Savepoint savepoint2 = conn.setSavepoint("ROWS_DELETED_"2");
      System.out.println("Deleting row....");
      SQL = "DELETE FROM Employees" +
                   "WHERE ID = 95";
      stmt.executeUpdate(SQL);  
	  //Step10:Now list all available records.
      sql = "SELECT id, first, last, age FROM Employees";
      rs = stmt.executeQuery(sql);
      System.out.println("List result set for reference....");
      printRs(rs);
      //Step10:Cleanup environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle JDBC error
      se.printStackTrace();
      // If there is an error, rollback the changes.
      System.out.println("Rolling back data here....");
	  try{
		 if(conn!=null)
            conn.rollback();
      }catch(SQLException se2){
         se2.printStackTrace();
      }//End try
   }catch(Exception e){
      //Handle Class.forName error
      e.printStackTrace();
   }finally{
      //Used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      
      }
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }//End try
   System.out.println("Goodbye!");
}//End main
   public static void printRs(ResultSet rs) throws SQLException{
      //Ensure we start from the first row
      rs.beforeFirst();
      while(rs.next()){
         //Search by column name
         int id = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         //Display values
         System.out.print("ID: ", + id);
         System.out.print("Age: ", + age);
         System.out.print("First: ", + first);
         System.out.println(", Last: " + last);
     }
     System.out.println();
   }//End of printRs()
}//End of JDBCExample

Now, let's compile the above example as follows:

C:\>javac JDBCExample.java
C:\>

RuntimeJDBCExampleIt will produce the following result-

C:\>java JDBCExample
Connecting to database...
Creating statement...
List result set for reference....
ID: 95, Age: 20, First: Sima, Last: Chug
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 30, First: Sumit, Last: Mittal
ID: 110, Age: 20, First: Sima, Last: Chug
Deleting row....
Deleting row....
List result set for reference....
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 30, First: Sumit, Last: Mittal
ID: 110, Age: 20, First: Sima, Last: Chug
Goodbye!
C:\>