A transaction represents a group of operations, used to perform a task.
Here are the most important points about Transaction Management in JDBC.
The basic transactions are of two types.
If all the operations are executed on one/same database, then it is called as local transaction.
If the operations are executed on more than one database then it is called as global transactions.
Example : If we transfer the money from account1 to account2 of same bank, then it is called as local transaction. If we transfer the money from account1 to account2 of different banks, then it is called as global or distributed transaction.
We can get the Transaction support in JDBC from Connection interface. The Connection interface given 3 methods to perform Transaction Management in JDBC.
Before going to begin the operations, first we need to disable the auto commit mode. This can be done by calling setAutoCommit(false).
By default, all operations done from the java program are going to execute permanently in database. Once the permanent execution happened in database, we can’t revert back them (Transaction Management is not possible).
If all operations are executed successfully, then we commit a transaction manually by calling the commit() method.
If any one of the operation failed, then we cancel the transaction by calling rollback() method.
connection.setAutoCommit(false);
try{
----------
----------
connection.commit();
}catch(Exception e){
connection.rollback();
}
Example Program
package com.java.session.ninteen;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JdbcTransactionManagementExample {
static final String DB_URL = "jdbc:mysql://localhost/emp";
static final String USER = "root";
static final String PASS = "PASSWORD";
static final String QUERY = "INSERT INTO EMP.EMPLOYEE VALUES(?,?,?,?)";
public static void main(String[] args) throws Exception {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection(DB_URL, USER, PASS);
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(QUERY);
preparedStatement.setInt(1, 15);
preparedStatement.setInt(2, 23);
preparedStatement.setString(3, "alikhan");
preparedStatement.setString(4, "navab");
preparedStatement.executeUpdate();
connection.commit();
System.out.println("Transaction is committed.");
} catch (Exception e) {
e.printStackTrace();
connection.rollback();
} finally {
try {
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}