01: import java.sql.Connection;
02: import java.sql.ResultSet;
03: import java.sql.Statement;
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 accountNumber the account number
24:       @param amount the amount to deposit
25:    */
26:    public void deposit(double amount)
27:       throws SQLException
28:    {
29:       Connection conn = SimpleDataSource.getConnection();
30:       Statement stat = conn.createStatement();
31:       stat.execute("UPDATE Account"
32:          + " SET Balance = Balance + " + amount
33:          + " WHERE Account_Number = " + accountNumber);      
34:       stat.close();
35:       conn.close();
36:    }
37: 
38:    /**
39:       Withdraws money from a bank account.
40:       @param accountNumber the account number
41:       @param amount the amount to withdraw
42:    */
43:    public void withdraw(double amount)
44:       throws SQLException
45:    {
46:       Connection conn = SimpleDataSource.getConnection();
47:       Statement stat = conn.createStatement();
48:       stat.execute("UPDATE Account"
49:          + " SET Balance = Balance - " + amount
50:          + " WHERE Account_Number = " + accountNumber);      
51:       stat.close();
52:       conn.close();
53:    }
54: 
55:    /**
56:       Gets the balance of a bank account.
57:       @param accountNumber the account number
58:       @return the account balance
59:    */
60:    public double getBalance()
61:       throws SQLException
62:    {
63:       double balance = 0;
64:       Connection conn = SimpleDataSource.getConnection();
65:       Statement stat = conn.createStatement();
66:       ResultSet result = stat.executeQuery("SELECT Balance"
67:          + " FROM Account WHERE Account_Number = "
68:          + accountNumber);
69:       if (result.next())
70:          balance = result.getDouble(1);
71:       result.close();
72:       stat.close();
73:       conn.close();
74:       return balance;
75:    }
76: 
77:    private int accountNumber;
78: }
79: