// Illustrate Transaction handling without container support. // This is example is from Java Server Programming J2EE Edition // by Wrox Press Ltd. // This client's second dataset leaves behind an inconsistent // table. import java.sql.Connection; import java.sql.DriverManager; public class Client1 { // The Access database located at D:\McCarthy\www\95-702\JDBCTransaction\AccountDB // has a table called Account and a DNS name of AccountDNS // The value in the amount field must be >= 0 and <= 15000. // The first transfer should work fine. /* private static final String ACCOUNT1 = "A32-116"; private static final String NAME1 = "Lynne Older"; private static final double AMOUNT1 = 10000.0; private static final String ACCOUNT2 = "A32-117"; private static final String NAME2= "Pat Mahar"; private static final double AMOUNT2 = 12000.0; private static final double TRANSFER_AMOUNT = 1000.0; */ // This transfer should not work correctly - we lose the money 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"); Account accountFrom = new Account(); accountFrom.read(accountIDFrom,con); Account accountTo = new Account(); accountTo.read(accountIDTo,con); accountFrom.setAmount(accountFrom.getAmount() - amount); accountTo.setAmount(accountTo.getAmount() + amount); accountFrom.update(con); accountTo.update(con); System.out.println("Funds Transfererred"); } catch(Exception e) { e.printStackTrace(); } finally { try { if(con != null) { con.close(); } } catch(Exception e) { System.out.println("Caught exception while closing"); } } } }