Wednesday, 1 October 2014

How to commit a transaction in JDBC

Usually a Connection object is used to connect to a databse. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

java.sql.Connection interface provides 'setAutoCommit' method to enable/disable auto commit mode.

void setAutoCommit(boolean autoCommit) throws SQLException
if autoCommit is true, enables the auto commit mode. Else disables auto commit mode. By default every connection to database is in auto-commit mode.

Lets take an example
/* 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);
        
        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
Dropping table employee

As you observe in the above program,

conn.setAutoCommit(false);
statement disables the auto commit mode. So you must explicitly commit the transactions.

conn.rollback();
Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object. So the records are not commited to the table employee.

Java.sql.Connection class provides 'commit' method to commit the transaction against the database.

void commit() throws SQLException
Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object. Call this method if auto-commit mode has been disabled.

Will call 'commit' method just before calling rollback 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);
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        
        System.out.println("Calling roll back operation");
        conn.commit();
        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
2 Arjun
Dropping table employee 




 
Prevoius                                                 Next                                                 Home

Commit Operation

The statements in a transaction can be either all committed or rolled back. A transaction begins with the first executable SQL statement. A transaction ends when it is committed or rolled back, either explicitly with a COMMIT or ROLLBACK statement or implicitly when a DDL statement is issued.



Prevoius                                                 Next                                                 Home

Transaction

Transaction is unit of work performed in database management system against a database.

Example
1. Transferring money from Account A to Account B
2. Booking a Movie ticket

A database transaction satisfies properties like Atomicity, consistency, Isolation, Durability,

a. Atomicity
A Transaction performed on a database must complete fully or have no effect. Suppose transferring money from account 'A' to account 'B' must performed completely. It shouldn't be in middle state like money deducted from Account 'A' and not credited to account 'B'.

b. Consistency
The guarantee that operations in transactions are performed accurately, correctly, and with validity, with respect to application semantic.

c. Isolation
Even though transactions can execute concurrently, it appears to each transaction that others executed either before or after it.

d. Durability
Transactions that have committed will survive permanently on any circumstances like system crash also.




Prevoius                                                 Next                                                 Home

Database Metadata

Metadata is the data that describes about data. Database metadata describes about specific characteristic of each data item in the database.

For example, Database metadata describes about tables, columns in each table, views in database, information about stored procedures.

JDBC provides below interfaces, to deal with database metadata.

DatabaseMetaData interface: provides information about the database

ResultSetMetaData interface: provides information about the columns of a ResultSet object

ParameterMetaData interface: provides information about the parameters to PreparedStatement commands

As you observe above image, the database 'world' has tables city, country, countrylanguage. Will retrieve the same information using jdbc.

/* 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();
        ResultSet rs = null;
        /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        DatabaseMetaData meta = conn.getMetaData();
        
        if(meta == null){
            System.out.println("No Support");
        }
        else{
            rs = meta.getTables(null, null, "%", null);
            while(rs.next()){
                System.out.println(rs.getString(3));
            }
        }
    rs.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
city
country
countrylanguage

String url = "jdbc:mysql://localhost/world";
Above url is used to connect to database 'world'.

DatabaseMetaData meta = conn.getMetaData();
Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.







Prevoius                                                 Next                                                 Home

How to Map SQL types to Java

Below table shows how a Java data type maps to JDBC SQL type.

Java Type
JDBC Type
String
CHAR, VARCHAR, or LONGVARCHAR
java.math.BigDecimal
NUMERIC
boolean
BIT
byte
TINYINT
short
SMALLINT
int
INTEGER
long
BIGINT
float
REAL
double
DOUBLE
byte[]
BINARY, VARBINARY or LONGVARBINARY
java.sql.Date
DATE
java.sql.Time
TIME
java.sql.Timestamp
TIMESTAMP
java.sql.Clob
CLOB
java.sql.Blob
BLOB
java.sql.Array
ARRAY
java.sql.Struct
STRUCT
java.sql.Ref
REF
Java class
JAVA_OBJECT



Prevoius                                                 Next                                                 Home

Load Driver using System.properties

By using 'setProperty' method of System class, you can load JDBC driver into JVM.

System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");

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

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
        System.out.println(System.getProperty("jdbc.drivers"));
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/sample";
        String userName = "root";
        String pasword = "tiger";
        Connection conn = DriverManager.getConnection(url, userName, pasword);
        
        /* 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 = "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
com.mysql.jdbc.Driver
Connecting to database
1 Krishna
2 Arjun
Dropping table employee

Prevoius                                                 Next                                                 Home

Load Driver by creating instance of Driver class

You can load the JDBC drivers by creating an object using the vendor's JDBC Driver class.

/* Step 1: Import sql package */
import java.sql.*;
import com.mysql.jdbc.Driver;

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");       
        Driver driver = new Driver();
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/sample";
        String userName = "root";
        String pasword = "tiger";
        Connection conn = DriverManager.getConnection(url, userName, pasword);
        
        /* 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 = "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
1 Krishna
2 Arjun
Dropping table employee



Prevoius                                                 Next                                                 Home