01: import java.sql.Connection;
02: import java.sql.ResultSet;
03: import java.sql.PreparedStatement;
04: import java.sql.SQLException;
05: 
06: /**
07:    A bank account has a balance that can be changed by 
08:    deposits and withdrawals.
09: */
10: public class BankAccount
11: {  
12:    /**
13:       Constructs a bank account with a given balance.
14:       @param anAccountNumber the account number
15:    */
16:    public BankAccount(int anAccountNumber)
17:    {  
18:       accountNumber = anAccountNumber;
19:    }
20: 
21:    /**
22:       Deposits money into a bank account.
23:       @param amount the amount to deposit
24:    */
25:    public void deposit(double amount)
26:          throws SQLException
27:    {
28:       Connection conn = SimpleDataSource.getConnection();
29:       try
30:       {
31:          PreparedStatement stat = conn.prepareStatement(
32:                "UPDATE Account"
33:                + " SET Balance = Balance + ?"
34:                + " WHERE Account_Number = ?");
35:          stat.setDouble(1, amount);
36:          stat.setInt(2, accountNumber);
37:          stat.executeUpdate();      
38:       }
39:       finally
40:       {
41:          conn.close();
42:       }
43:    }
44: 
45:    /**
46:       Withdraws money from a bank account.
47:       @param amount the amount to withdraw
48:    */
49:    public void withdraw(double amount)
50:          throws SQLException
51:    {
52:       Connection conn = SimpleDataSource.getConnection();
53:       try
54:       {
55:          PreparedStatement stat = conn.prepareStatement(
56:                "UPDATE Account"
57:                + " SET Balance = Balance - ?"
58:                + " WHERE Account_Number = ?");
59:          stat.setDouble(1, amount);
60:          stat.setInt(2, accountNumber);
61:          stat.executeUpdate();      
62:       }
63:       finally
64:       {
65:          conn.close();
66:       }
67:    }
68: 
69:    /**
70:       Gets the balance of a bank account.
71:       @return the account balance
72:    */
73:    public double getBalance()
74:          throws SQLException
75:    {
76:       Connection conn = SimpleDataSource.getConnection();
77:       try
78:       {
79:          double balance = 0;
80:          PreparedStatement stat = conn.prepareStatement(
81:                "SELECT Balance FROM Account WHERE Account_Number = ?");
82:          stat.setInt(1, accountNumber);
83:          ResultSet result = stat.executeQuery();
84:          if (result.next())
85:             balance = result.getDouble(1);
86:          return balance;
87:       }
88:       finally
89:       {
90:          conn.close();
91:       }
92:    }
93: 
94:    private int accountNumber;
95: }
96: