// Illustrate Transaction handling without container support. // This is example is from Java Server Programming J2EE Edition // by Wrox Press Ltd. import java.sql.Connection; import java.sql.DriverManager; public class Client2 { // The Access database located at D:\McCarthy\www\95-702\examples\JDBCTransaction\AccountDB // has a table called Account and a DNS name of AccountDNS // The value in the amount field must be >= 0 and <= 15000. // This transfer should not work correctly private static final String ACCOUNT1 = "B32-116"; private static final String NAME1= "Cristina Couglin"; private static final double AMOUNT1 = 10000.0; private static final String ACCOUNT2 = "B32-117"; private static final String NAME2= "Mary Klopot"; private static final double AMOUNT2 = 14000.0; private static final double TRANSFER_AMOUNT = 2000.0; public static void main(String args[]) throws Exception { DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver()); createAccounts(); transfer(ACCOUNT1, ACCOUNT2, TRANSFER_AMOUNT); } private static void createAccounts() { Connection con = null; try { con = DriverManager.getConnection("jdbc:odbc:AccountDSN"); Account account1 = new Account(); account1.create(ACCOUNT1,NAME1,AMOUNT1,con); Account account2 = new Account(); account2.create(ACCOUNT2,NAME2,AMOUNT2,con); System.out.println("Acoounts created"); } catch(Exception e) { System.out.println("Exception thrown"); e.printStackTrace(); } finally { try { if(con != null) { con.close(); } } catch(Exception e) { System.out.println("Exception while closing"); } } } private static void transfer(String accountIDFrom, String accountIDTo, double amount) { Connection con = null; try { con = DriverManager.getConnection("jdbc:odbc:AccountDSN"); con.setAutoCommit(false); System.out.println("Reading from source account"); Account accountFrom = new Account(); accountFrom.read(accountIDFrom,con); System.out.println("Reading from destination account"); Account accountTo = new Account(); accountTo.read(accountIDTo,con); System.out.println("Reducing source account by "+ amount); accountFrom.setAmount(accountFrom.getAmount() - amount); System.out.println("Adding " + amount + " to destination account"); accountTo.setAmount(accountTo.getAmount() + amount); accountFrom.update(con); accountTo.update(con); System.out.println("Funds Transfererred about to commit"); con.commit(); } catch(Exception e) { try { System.out.println("Exception throw about to rollback"); con.rollback(); } catch(Exception re) { System.out.println("Rollback exception?"); } e.printStackTrace(); } finally { try { if(con != null) { con.close(); } } catch(Exception e) { System.out.println("Caught exception while closing"); } } } }