Java Reference
In-Depth Information
Example 17−5: RemoteDBBankServer.java (continued)
/** The constructor. Just save the database connection object away */
public RemoteDBBankServer(Connection db) throws RemoteException {
this.db = db;
}
/** Open an account */
public synchronized void openAccount(String name, String password)
throws RemoteException, BankingException
{
// First, check if there is already an account with that name
Statement s = null;
try {
s = db.createStatement();
s.executeQuery("SELECT * FROM accounts WHERE name='" + name + "'");
ResultSet r = s.getResultSet();
if (r.next()) throw new BankingException("Account name in use.");
// If it doesn't exist, go ahead and create it Also, create a
// table for the transaction history of this account and insert an
// initial transaction into it.
s = db.createStatement();
s.executeUpdate("INSERT INTO accounts VALUES ('" + name + "', '" +
password + "', 0)");
s.executeUpdate("CREATE TABLE " + name +
"_history (msg VARCHAR(80))");
s.executeUpdate("INSERT INTO " + name + "_history " +
"VALUES ('Account opened at " + new Date() + "')");
// And if we've been successful so far, commit these updates,
// ending the atomic transaction. All the methods below also use
// this atomic transaction commit/rollback scheme
db.commit();
}
catch(SQLException e) {
// If an exception was thrown, "rollback" the prior updates,
// removing them from the database. This also ends the atomic
// transaction.
try { db.rollback(); } catch (Exception e2) {}
// Pass the SQLException on in the body of a BankingException
throw new BankingException("SQLException: " + e.getMessage() +
": " + e.getSQLState());
}
// No matter what happens, don't forget to close the DB Statement
finally { try { s.close(); } catch (Exception e) {} }
}
/**
* This convenience method checks whether the name and password match
* an existing account. If so, it returns the balance in that account.
* If not, it throws an exception. Note that this method does not call
* commit() or rollback(), so its query is part of a larger transaction.
**/
public int verify(String name, String password)
throws BankingException, SQLException
{
Statement s = null;
try {
s = db.createStatement();
Search WWH ::




Custom Search