cessor {
//Column definitions here (i.e., COLUMN_USERNAME, etc...)
..
public Object[] process(ResultSet rs) throws SQLException {
//Where we will collect all returned users
List users = new ArrayList();
User user = null;
//If there were results returned, then process them
while(rs.next()) {
user = new User(rs.getInt(COLUMN_ID), rs.getString(COLUMN_USERNAME),
rs.getString(COLUMN_FIRST_NAME), rs.getString(COLUMN_LAST_NAME),
rs.getString(COLUMN_EMAIL));
users.add(user);
}
return users.toArray(new User[users.size()]);
最后,我们将写一个方法来执行查询并且返回User对象:
public User getUser(int userId) {
//Get a SQL processor and execute the query
SQLProcessor processor = new SQLProcessor();
Object[] users = processor.executeQuery(SQL_GET_USER_BY_ID,
new Object[] {new Integer(userId)},
new UserResultProcessor());
//And just return the first User object
return (User) users[0];
}
这就是全部。我们只需要一个处理类和一个简单的方法,我们就可以无需进行直接的连接维护、语句和异常处理。此外,如果我们拥有另外一个查询由用户表中得到一行,例如通过用户名或者密码,我们可以重新使用UserResultProcessor。我们只需要插入一个不同的SQL语句,并且可以重新使用以前方法的用户处理器。由于返回行的元数据并不依赖查询,所以我们可以重新使用结果处理器。
消除JDBC的瓶颈(4)
时间:2010-09-13
更新的架构
那么数据库更新又如何呢?我们可以用类似的方法处理,只需要进行一些修改就可以了。首先,我们必须增加两个新的方法到SQLProcessor类。它们类似executeQuery()和handleQuery()方法,除了你无需处理结果集,你只需要将更新的行数作为调用的结果:
public void executeUpdate(String sql, Object[] pStmntValues,
UpdateProcessor processor) {
//Get a connection
Connection conn = ConnectionManager.getConnection();
//Send it off to be executed
handleUpdate(sql, pStmntValues, processor, conn);
//Close the connection
closeConn(conn);
}
protected void handleUpdate(String sql, Object[] pStmntValues,
UpdateProcessor processor, Connection conn) {
//Get a prepared statement to use
PreparedStatement stmnt = null;
try {
//Get an actual prepared statement
stmnt = conn.prepareStatement(sql);
//Attempt to stuff this statement with the given values. If
//no values were given, then we can skip this step.
if(pStmntValues != null) {
PreparedStatementFactory.buildStatement(stmnt, pStmntValues);
}
//Attempt to execute the statement
int rows = stmnt.executeUpdate();
//Now hand off the number of rows updated to the processor
processor.process(rows);
//Close out the statement only. The connection will be closed by the
//caller.
closeStmnt(stmnt);
//Any SQL exceptions that occur should be recast to our runtime query
//exception and thrown from here
} catch(SQLException e) {
String message = "Could not perform the update for " + sql;
//Close out all resources on an exception
closeConn(conn);
closeStmnt(stmnt);
//And rethrow as our exception
throw new DatabaseUpdateException(message);
}
}
这些方法和查询处理方法的区别仅在于它们是如何处理调用的结果:由于一个更新的操作只返回更新的行数,因此我们无需结果处理器。我们也可以忽略更 |