You are on page 1of 1

EXAMPLE OF TRANSACTION

package com.javasree.jdbc;
import java.sql.*;
import com.javasree.util.*;
class TxDemo
{
public static void main(String as[])
{
Account acc=new Account();
acc.transfer(99,88,5000);
}
}
class Account
Transaction
{
int bal;
int dabal,sabal,danbal,sanbal;
public void transfer(int sa,int da,int amt)
{
Connection con=null;
PreparedStatement ps1=null;
PreparedStatement ps2=null;
try
{
con=DBUtil.getOracleConnection();
//start transaction
con.setAutoCommit(false);
//op 1 select
ps1=con.prepareStatement("select bal from account
where accno=?");
ps1.setInt(1,da);
ResultSet rs1=ps1.executeQuery();
if(rs1.next())
{
dabal=rs1.getInt(1);
}
else
{
throw new Exception();
}
danbal=dabal+amt;

//op 3 select
ps1.setInt(1,sa);
rs1=ps1.executeQuery();
if(rs1.next())
{
sabal=rs1.getInt(1);
}
else
{
throw new Exception();
}
if(sabal>=amt)
{
sanbal=sabal-amt;
}
else
{
throw new Exception();
}
//op4 update
ps2.setInt(1,sanbal);
ps2.setInt(2,sa);
ps2.executeUpdate();
con.commit();
}
catch(Exception e)
{
Acct_Transaction
try
{
con.rollback();
}
catch(Exception e1){ }
System.out.println(e);
}
finally
{
DBUtil.cleanup(con,ps1);
}

Acct_Transaction

//op2 update
ps2=con.prepareStatement("update account set
bal=? where accno=?");
ps2.setInt(1,danbal);
ps2.setInt(2,da);
ps2.executeUpdate();

}
}