ORIGIN

JDBC Apache-DBUtils

JDBC 1 mins278 words

This article is note about learning Apache-DBUtils.

commons-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.

  1. Download the jar file https://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi
  2. QueryRunner runner = new QueryRunner();

how to use

  1. insert, delete, update: runner.update(conn, sql, "", "");

  2. select:

    • for one row of data, use BeanHandler

      1
      2
      BeanHandler<Customer> handler = new BeanHandler<>(Customer.class);
      Customer costomer = runner.query(conn, sql, handler, 23);
    • for multiple row of data, use BeanListHandler

      1
      2
      BeanListHandler<Customer> handler = new BeanListHandler<>(Customer.class);
      list<Customer> list = runner.query(conn, sql, handler, 23);
    • to get result in map, use MapListHandler or MapListHandler. Map keys are the column name in table, values are values in table.

      1
      2
      MapHandler handler = new MapHandler();
      Map<String, Object> map = runner.query(conn, sql, handler, "");
    • there is also ArrayHandler, ArrayListHandler

  3. select for specific value , use ScalarHandler

    1
    2
    3
    String sql = "select count(*) from customers";
    ScalarHandler handler = new ScalarHandler();
    Long cout = runner.query(conn, sql, handler);
  4. self define

    1
    2
    3
    4
    5
    6
    ResultSetHandler<Customer> handler = new ResultSetHandler<Customer>() {
    @Override
    public Customer handle(ResultSet rs) throws SQLException {
    // ...
    }
    }
  5. close

    1
    2
    3
    4
    5
    try {
    DbUtils.close(conn);
    } catch (Exception e) {
    e.printStackTrace();
    }

    or

    1
    DbUtils.closeQuietly(conn);
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|