JDBC Utility Component -- Examples Yoav Shapira

This page provides examples that show how the DbUtils component may be used.

The core classes/interfaces in DbUtils are QueryRunner and ResultSetHandler. The following example demonstrates how these classes are used together.

DataSource ds = // somehow get DataSource;

// Step 1.
QueryRunner run = new QueryRunner(ds);

// Step 2.
ResultSetHandler h = new BeanHandler(Person.class);

// Step 3.
Person p = (Person) run.query("SELECT * FROM Person WHERE name=?", "John Doe", h); 

Explanation

  1. Configure QueryRunner with the DataSource. Note that QueryRunner has methods that take a java.sql.Connection so you are not required to use DataSources.
  2. Implement the ResultSetHandler interface or use one of the provided implementations. This one converts a ResultSet row into a bean.
  3. Execute the SQL statement with one replacement parameter and return the results in a new Person object (generated by the handler in step 2).