A distributed transaction is a set of operations on data that is performed across two or more data repositories (especially databases). It is typically coordinated across separate nodes connected by a network, but may also span multiple databases on a single server.
Distributed Transaction Demo Code (Java + MySQL)
// Demo Implementation of Distributed Transactionimportjava.sql.*;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.Savepoint;
importjava.sql.Statement;
importjava.util.Scanner;
importjava.sql.Connection;
publicclass Distributed {
/**
*@paramargs
*/
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=newScanner(System.in);
System.out.println("Enter Your Account Number:");
intfromAccountNo=sc.nextInt();
System.out.println("Enter Reciever Account Number:");
inttoAccountNo=sc.nextInt();
System.out.println("Enter Amount to be Transferred:");
int amount=sc.nextInt();
String url = "jdbc:mysql://localhost:3306/transaction";
String url1 = "jdbc:mysql://localhost:3306/tran";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
PreparedStatementpst=null;
ResultSet res=null;
ResultSet r1=null;
Connection con=null;
Statement st=null;
Statement st1=null;
intfromBalance=0;
inttoBalance=0;
try{
Class.forName(driver);
con=DriverManager.getConnection(url, user, pass);
con.setAutoCommit(false);
Connection con1 = DriverManager.getConnection(url1, user, pass);
Savepoint save1=con.setSavepoint();
st =con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.TYPE_FORWARD_ONLY);
String str="SELECT BALANCE from SBH where ACCOUNT_NUMBER="+fromAccountNo+"";
res = st.executeQuery(str);
while(res.next()){
System.out.println(str);
fromBalance= res.getInt(1);
System.out.println(+fromBalance);
}
fromBalance=fromBalance-amount;
pst=con.prepareStatement("UPDATE SBH SET BALANCE=? WHERE ACCOUNT_NUMBER=?");
res.first();
pst.setInt(1, fromBalance);
pst.setInt(2, fromAccountNo);
int re= pst.executeUpdate();
System.out.println("hii");
if(re!=0){
st1= con1.createStatement();
String strnew="SELECT BALANCE from BOI where ACCOUNT_NUMBER="+toAccountNo+"";
System.out.println(+toAccountNo);
st1 = con1.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.TYPE_FORWARD_ONLY);
//System.out.println("hiivvhh11");
r1= st1.executeQuery(strnew);
//System.out.println("hiivvhh");
while (r1.next())
{
toBalance = r1.getInt(1);
System.out.println("hiiii second");
}
toBalance=amount+toBalance;
PreparedStatement pst1 = con1.prepareStatement("UPDATE BOI SET BALANCE=? WHERE ACCOUNT_NUMBER=?");
pst1.setInt(1, toBalance);
pst1.setInt(2, toAccountNo);
int re1= pst1.executeUpdate();
if(re1!=0){
System.out.println("Amount Transferred Successfully");
con.commit();
}else{
System.out.println("Unable to transfer");
con.rollback(save1);
}
}
}
catch(Exception e){
}
}
}