
Transaction is a complete task which is a combination of the smaller tasks. For the major task to be completed, the smaller tasks need to be successfully completed. If any one task fails then all the previous tasks are reverted to the original state.
For example if you are withdrawing money it consist getting money, reducing the balance from account and also printing a slip. If anything gets failed then all the things should be converted to its previous state. In order to achieve this type of functionality where all the queries should be completed otherwise the task should be rolled back is acheieve by three methods rollback(), commit() and setAutoCommit().
By default the connection commits all the changes once it is done with the single query. This can be stopped by calling setAutoCommit(false) on connection object. Now for every transaction user has to explicitly call commit() method only the changes get reflected otherwise changes wont be shown in the database. Rollback() method gets called for withdrawing all the changes done by the queries in the database.
Note:- The program will not change any data as the commit() is called after rollback().
package com.visualbuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BasicTransactionExample {
public static void main(String[] args) {
try {
/** Loading the driver*/
Class.forName("com.mysql.jdbc.Driver");
/** Getting Connection*/
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
/** Creating Statement*/
con.setAutoCommit(false);
Statement stmt= con.createStatement();
stmt.execute("delete from visualbuilder");
//Commits the transaction
System.out.println("Commit called ");
con.rollback();
con.commit();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:-
Commit called
Java Discussion
- - Java web application
- - Difference between BMT an
- - Replace getParameterValue
- - Interviewing Next week -
- - Sudoku solver




