Wednesday, 1 October 2014

Connection interface

Connection object is used to logically connect to a database. By using connection object you can perform commit and roll back operation, get the metadata, set the save points and create statements, prepareStatement etc.,



Prevoius                                                 Next                                                 Home

Debug problems in JDBC

DriverManager class provides 'setLogWriter' method, which Sets the logging /tracing PrintWriter object that is used by the DriverManager and all drivers.

If you are using DataSource, XADataSource classes, similar method is available for logging.

/* Step 1: Import sql package */
import java.sql.*;
import java.io.*;

public class SampleApp {
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException, FileNotFoundException{
        PrintWriter pw;
        pw = new PrintWriter(new FileOutputStream("debug.txt"));
        
        DriverManager.setLogWriter(pw);
        
        Connection conn = getConnection();
        conn.setAutoCommit(false);
          /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        query = "INSERT INTO employee values(3, \"Joel\")";
        stmt.execute(query);
        
        System.out.println("Calling roll back operation");
        
        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
        System.out.println("Dropping table employee");
        query = "DROP TABLE employee";
        stmt.execute(query);
        
    rs.close();
        stmt.close();
        conn.close();
        pw.close();
    }
}


Output
Loading/Registering driver
Connecting to database
Calling roll back operation
1 Krishna
2 Arjun
3 Joel
Dropping table employee

PrintWriter pw;
pw = new PrintWriter(new FileOutputStream("debug.txt"));
  Above statement creates a PrintWriter object.

DriverManager.setLogWriter(pw);
   Sets the logging/tracing PrintWriter object that is used by the DriverManager and all drivers.

After running above application, debug.txt contains below information.

registerDriver: com.mysql.jdbc.Driver@1f792cf
DriverManager.getConnection("jdbc:mysql://localhost/world")
    trying org.apache.derby.jdbc.AutoloadedDriver40
    trying org.apache.derby.jdbc.ClientDriver40
    trying com.mysql.jdbc.Driver
getConnection returning com.mysql.jdbc.Driver


Prevoius                                                 Next                                                 Home

Rollback to savepoint

java.sql.Connection interface provides rollback method to rollback to savepoint.

void rollback(Savepoint savepoint) throws SQLException
Undoes all changes made after the given savepoint object was set.

Step 1: Disable auto commit mode.
   Ex:
   Connection conn = getConnection();
   conn.setAutoCommit(false);

Step 2: Create a savepoint
   Ex: Savepoint s1 = conn.setSavepoint();

Step 3: Call the rollback method to the save point
   Ex : conn.rollback(s1);

/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        
        Connection conn = getConnection();
        conn.setAutoCommit(false);
          /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        
        /* Creating a savepoint */
        Savepoint s1 = conn.setSavepoint();
        
        query = "INSERT INTO employee values(3, \"Joel\")";
        stmt.execute(query);
        
        System.out.println("Calling roll back operation");
        
        conn.rollback(s1);
        
        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
        System.out.println("Dropping table employee");
        query = "DROP TABLE employee";
        stmt.execute(query);
        
 rs.close();
        stmt.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
Calling roll back operation
1 Krishna
2 Arjun
Dropping table employee




Prevoius                                                 Next                                                 Home

How to set savepoint

java.sql.Connection interface provides 'setSavepoint' method to set the savepoint.

'setSavepoint' method available in two variants.

Savepoint setSavepoint() throws SQLException
Creates an unnamed savepoint in the current transaction and returns the new Savepoint object that represents it.

Savepoint setSavepoint(String name) throws SQLException
Creates a savepoint with the given name in the current transaction and returns the new Savepoint object that represents it.

/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        
        Connection conn = getConnection();
        conn.setAutoCommit(false);
          /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        
        Savepoint s1 = conn.setSavepoint();
        
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        
        System.out.println("Calling roll back operation");
        
        conn.rollback(s1);
        
        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
        System.out.println("Dropping table employee");
        query = "DROP TABLE employee";
        stmt.execute(query);
        
 rs.close();
        stmt.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
Calling roll back operation
1 Krishna
Dropping table employee

Savepoint s1 = conn.setSavepoint();
Above statement creates a savepoint.

conn.rollback(s1);
Undoes all changes made after the Savepoint 's1' object was set.





Prevoius                                                 Next                                                 Home

Savepoint interface

When a transaction is rolled back to a savepoint all changes made after that savepoint are undone.

public interface Savepoint {
    int getSavepointId() throws SQLException;
    String getSavepointName() throws SQLException;
}

int getSavepointId() throws SQLException
Return the numeric ID of this savepoint.

String getSavepointName() throws SQLException
Returns the name of this savepoint.



Prevoius                                                 Next                                                 Home

How to Perform rollback operation in JDBC

java.sql.Connection interface provides rollback method to perform rollback operation.

rollback method available in two variants.

void rollback() throws SQLException
Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.

void rollback(Savepoint savepoint) throws SQLException
Undoes all changes made after the given Savepoint object was set.

To perform rollback operations follow below steps.
Step 1: First disable autocommit mode, otherwise every sql statement get committed after execution.

Step 2: call rollback() where ever you want to perform roll back operation.
/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        
        Connection conn = getConnection();
        conn.setAutoCommit(false);
          /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        conn.commit();
        
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        
        System.out.println("Calling roll back operation");
        
        conn.rollback();
        
        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
        System.out.println("Dropping table employee");
        query = "DROP TABLE employee";
        stmt.execute(query);
        
 rs.close();
        stmt.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
Calling roll back operation
1 Krishna
Dropping table employee

As you observe the above program, auto commit mode is disabled .After inserting first record (1, Krishna), application called commit operation. But commit operation is not called after inserting second record, So when the application calls roll back operation, the data restored to previously committed state, and restores record 1 only.


 


Prevoius                                                 Next                                                 Home

Rollback operation

A rollback is an operation which returns the database to some previous state. Rollbacks are important to maintain database integrity.



Prevoius                                                 Next                                                 Home