Apache官方参考文档:
// Create a ResultSetHandler implementation to convert the
// first row into an Object[].
ResultSetHandler h = new ResultSetHandler() {
public Object handle(ResultSet rs) throws SQLException {
if (!rs.next()) {
return null;
}
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Object[] result = new Object[cols];
for (int i = 0; i < cols; i++) {
result[i] = rs.getObject(i + 1);
}
return result;
}
};
// Create a QueryRunner that will use connections from
// the given DataSource
QueryRunner run = new QueryRunner(dataSource);
// Execute the query and get the results back from the handler
Object[] result = (Object[]) run.query(
"SELECT * FROM Person WHERE name=?", "John Doe", h);
ResultSetHandler h = ... // Define a handler the same as above example
// No DataSource so we must handle Connections manually
QueryRunner run = new QueryRunner();
Connection conn = ... // open a connection
try{
Object[] result = (Object[]) run.query(
conn, "SELECT * FROM Person WHERE name=?", "John Doe", h);
// do something with the result
} finally {
// Use this helper method so we don't have to check for null
DbUtils.close(conn);
}
QueryRunner run = new QueryRunner( dataSource ); try { // Create an object array to hold the values to insert Object[] insertParams = {"John Doe", new Double( 1.82 )}; // Execute the SQL update statement and return the number of // inserts that were made int inserts = run.update( "INSERT INTO Person (name,height) VALUES (?,?)", insertParams ); // Now it's time to rise to the occation... Object[] updateParams = {new Double( 2.05 ), "John Doe"}; int updates = run.update( "UPDATE Person SET height=? WHERE name=?", updateParams ); } catch(SQLException sqle) { // Handle it }
QueryRunner run = new QueryRunner(dataSource);
// Use the BeanHandler implementation to convert the first
// ResultSet row into a Person JavaBean.
ResultSetHandler h = new BeanHandler(Person.class);
// Execute the SQL statement with one replacement parameter and
// return the results in a new Person object generated by the BeanHandler.
Person p = (Person) run.query(
"SELECT * FROM Person WHERE name=?", "John Doe", h);
QueryRunner run = new QueryRunner(dataSource); // Use the BeanListHandler implementation to convert all // ResultSet rows into a List of Person JavaBeans. ResultSetHandler h = new BeanListHandler(Person.class); // Execute the SQL statement and return the results in a List of // Person objects generated by the BeanListHandler. List persons = (List) run.query("SELECT * FROM Person", h);