This article is note about learning Apache-DBUtils.
The Commons DbUtils library is a small set of classes designed to make working with JDBC easier. JDBC resource cleanup code is mundane, error prone work so these classes abstract out all of the cleanup tasks from your code leaving you with what you really wanted to do with JDBC in the first place: query and update data.
This can replace the baseDao
Code we write in the previous articles.
QueryRunner runner = new QueryRunner();
insert, delete, update: runner.update(conn, sql, "", "");
select:
for one row of data, use BeanHandler
1 | BeanHandler<Customer> handler = new BeanHandler<>(Customer.class); |
for multiple row of data, use BeanListHandler
1 | BeanListHandler<Customer> handler = new BeanListHandler<>(Customer.class); |
to get result in map, use MapListHandler
or MapListHandler
. Map keys are the column name in table, values are values in table.
1 | MapHandler handler = new MapHandler(); |
there is also ArrayHandler
, ArrayListHandler
select for specific value , use ScalarHandler
1 | String sql = "select count(*) from customers"; |
self define
1 | ResultSetHandler<Customer> handler = new ResultSetHandler<Customer>() { |
close
1 | try { |
or
1 | DbUtils.closeQuietly(conn); |