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