DbUtils: JDBC Utility Component Examples

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

Basic Usage

DbUtils is a very small library of classes so it won't take long to go through the javadocs for each class. The core classes/interfaces in DbUtils are QueryRunner and ResultSetHandler. You don't need to know about any other DbUtils classes to benefit from using the library. The following example demonstrates how these classes are used together.

// Create a ResultSetHandler implementation to convert the
// first row into an Object[].
ResultSetHandler<Object[]> h = new ResultSetHandler<Object[]>() {
    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 = ; i < cols; i++) {
            result[i] = rs.getObject(i + );
        }         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 = run.query(
    "SELECT * FROM Person WHERE name=?", h, "John Doe");

You could also perform the previous query using a java.sql.Connection object instead of a DataSource. Notice that you are responsible for closing the Connection in this example.

ResultSetHandler<Object[]> 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 = run.query(
        conn, "SELECT * FROM Person WHERE name=?", h, "John Doe");
        // do something with the result
       
} finally {
    // Use this helper method so we don't have to check for null
    DbUtils.close(conn);  
}

You can not only fetch data from the database - you can also insert or update data. The following example will first insert a person into the database and after that change the person's height.

QueryRunner run = new QueryRunner( dataSource );
try
{
    // Execute the SQL update statement and return the number of
    // inserts that were made
    int inserts = run.update( "INSERT INTO Person (name,height) VALUES (?,?)",
                              "John Doe", 1.82 );
    // The line before uses varargs and autoboxing to simplify the code     // Now it's time to rise to the occation...
    int updates = run.update( "UPDATE Person SET height=? WHERE name=?",
                              2.05, "John Doe" );
    // So does the line above
}
catch(SQLException sqle) {
    // Handle it
}

For long running calls you can use the AsyncQueryRunner to execute the calls asynchronously. The AsyncQueryRunner class has the same methods as the QueryRunner calls; however, the methods return a Callable.

ExecutorCompletionService<Integer> executor =
    new ExecutorCompletionService<Integer>( Executors.newCachedThreadPool() );
AsyncQueryRunner asyncRun = new AsyncQueryRunner( dataSource ); try
{
    // Create a Callable for the update call
    Callable<Integer> callable = asyncRun.update( "UPDATE Person SET height=? WHERE name=?",
                                                  2.05, "John Doe" );
    // Submit the Callable to the executor
    executor.submit( callable );
} catch(SQLException sqle) {
    // Handle it
} // Sometime later (or in another thread)
try
{
   // Get the result of the update
   Integer updates = executor.take().get();
} catch(InterruptedException ie) {
    // Handle it
}

ResultSetHandler Implementations

In the examples above we implemented the ResultSetHandler interface to turn the first row of the ResultSet into an Object[]. This is a fairly generic implementation that can be reused across many projects. In recognition of this DbUtils provides a set of ResultSetHandler implementations in the org.apache.commons.dbutils.handlers package that perform common transformations into arrays, Maps, and JavaBeans. There is a version of each implementation that converts just the first row and another that converts all rows in the ResultSet.

We'll start with an example using the BeanHandler to fetch one row from the ResultSet and turn it into a JavaBean.

QueryRunner run = new QueryRunner(dataSource);

// Use the BeanHandler implementation to convert the first
// ResultSet row into a Person JavaBean.
ResultSetHandler<Person> h = new BeanHandler<Person>(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 = run.query(
    "SELECT * FROM Person WHERE name=?", h, "John Doe");

This time we will use the BeanListHandler to fetch all rows from the ResultSet and turn them into a List of JavaBeans.

QueryRunner run = new QueryRunner(dataSource);

// Use the BeanListHandler implementation to convert all
// ResultSet rows into a List of Person JavaBeans.
ResultSetHandler<List<Person>> h = new BeanListHandler<Person>(Person.class); // Execute the SQL statement and return the results in a List of
// Person objects generated by the BeanListHandler.
List<Person> persons = run.query("SELECT * FROM Person", h);

Custom RowProcessor

Each of the provided ResultSetHandler implementations accept a RowProcessor to do the actual conversion of rows into objects. By default the handlers use the BasicRowProcessorimplementation but you can implement a custom version to plug in. Probably the most common customization is to implement the toBean() method to handle custom database datatype issues.

Custom BeanProcessor

BasicRowProcessor uses a BeanProcessor to convert ResultSet columns into JavaBean properties. You can subclass and override processing steps to handle datatype mapping specific to your application. The provided implementation delegates datatype conversion to the JDBC driver.

BeanProcessor maps columns to bean properties as documented in the BeanProcessor.toBean() javadoc. Column names must match the bean's property names case insensitively. For example, the firstname column would be stored in the bean by calling its setFirstName() method. However, many database column names include characters that either can't be used or are not typically used in Java method names. You can do one of the following to map these columns to bean properties:

  1. Alias the column names in the SQL so they match the Java names: select social_sec# as socialSecurityNumber from person
  2. Subclass BeanProcessor and override the mapColumnsToProperties() method to strip out the offending characters.

DbUtils使用例子的更多相关文章

  1. apache DBUtils 使用例子demo

    转自:http://blog.csdn.net/earbao/article/details/44901061 apache DBUtils是java编程中的数据库操作实用工具,小巧简单实用, 1.对 ...

  2. DBUtils 增删改查例子

    sql CREATE TABLE [dbo].[Person] ( , ) NOT NULL , ) COLLATE Chinese_PRC_CI_AS NULL , [age] [int] NULL ...

  3. Python DBUtils

    1 简介 DBUtils是一套Python数据库连接池包,并允许对非线程安全的数据库接口进行线程安全包装.DBUtils来自Webware for Python. DBUtils提供两种外部接口: P ...

  4. 3. Android框架和工具之 xUtils(DbUtils )

    1. xUtils简介 xUtils 包含了很多实用的android工具.xUtils 最初源于Afinal框架,进行了大量重构,使得xUtils支持大文件上传,更全面的http请求协议支持(10种谓 ...

  5. Java学习之DBUtils工具的学习

    简介 commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影 ...

  6. Apache Commons DbUtils 快速上手

    原文出处:http://lavasoft.blog.51cto.com/62575/222771 Hibernate太复杂,iBatis不好用,JDBC代码太垃圾,DBUtils在简单与优美之间取得了 ...

  7. JavaWeb之DBUtils

    一.什么是DBUtils及作用 DBUtils是apache公司写的.DBUtils是java编程中的数据库操作实用工具,小巧简单实用. DBUtils封装了对JDBC的操作,简化了JDBC操作.可以 ...

  8. JDBC第四篇--【数据库连接池、DbUtils框架、分页】

    1.数据库连接池 什么是数据库连接池 简单来说:数据库连接池就是提供连接的. 为什么我们要使用数据库连接池 数据库的连接的建立和关闭是非常消耗资源的 频繁地打开.关闭连接造成系统性能低下 编写连接池 ...

  9. JDBC开源框架:DBUtils使用入门

    在单元测试过程中,只涉及到数据库的直接操作来验证业务逻辑是否正确的情况,DBUtils非常适合使用.它结构简单,包小,友好处理掉那些jdbc异常,让你更专注于业务代码,而非底层的操作.官网对它的定义: ...

随机推荐

  1. web前端基础——初识HTML DOM编程

    1 HTML DOM编程概述 文件对象模型(Document Object Model,简称DOM),是W3C组织推荐的处理HTML的标准编程接口.由于HTML文档被浏览器解析后就是一棵DOM树,要改 ...

  2. [推荐]Bitnami 开源软件包安装解决方案

    [推荐]Bitnami 开源软件包安装解决方案 Bitnami is an app store for server software. Install your favorite applicati ...

  3. 诚聘Android开发工程师

    职位要求1.有1年以上Android应用项目经验或相关经验: 2.熟悉Android操作系统和Android SDK,GUI编程及GDI的使用:熟练掌握Android 的 UI 系统控件及常用布局.动 ...

  4. 【转】Xcode概览(Xcode 6版):循序渐进认识Xcode

    该系列文章翻译自苹果的Xcode Overview文档,对大部分开发者来说,已经非常熟悉Xcode的功能和特性,不过伴随着iOS 8 SDK的发布,Xcode 6中也有些许调整,所以对该文档进行了翻译 ...

  5. PHP ERROR : Call to undefined function curl_init()

    在使用PHP 的Curl方法时出现了以下错误 可能的解决办法: 在php.ini 中确保 启用了php_curl.dll组件 确保PHP版本 (PHP 4 >= 4.0.2, PHP 5, PH ...

  6. asp.net core 之静态文件目录的操作

    文章前言 之前写了一篇关于模拟登录的文章,自我感觉内容不太丰富,今天的这篇文章,希望在内容上能丰富些.本人缺少写文章的经验,技术上也是新手,但我会努力的,希望大家多多支持小弟. asp.net cor ...

  7. Eclipse远程调试HDP源代码

    使用的是自己编译的HDP2.3.0的源代码编译的集群,此文介绍如何使用Eclipse远程调试Hadoop内核源代码,以调试namenode为例进行介绍. 在/usr/hdp/2.3.0.0-2557/ ...

  8. Linux shell crontab expdp 定时任务逻辑备份 定时删除旧文件

    点击进入:Window bat expdp 定时任务逻辑备份 定时删除N天前的旧文件 创建sh脚本 [oracle@localhost ~]$ vi logicbackup.sh 添加脚本内容 #!/ ...

  9. 命令行模式下 MYSQL导入导出.sql文件的方法

    一.MYSQL的命令行模式的设置:桌面->我的电脑->属性->环境变量->新建->PATH=“:path\mysql\bin;”其中path为MYSQL的安装路径.二.简 ...

  10. 物料分类账 [COML] PART 2 - 总体流程

    核心流程概要: [1]. 分类账在物料主数据的影响 首先描述下SAP中物料价格的 物料主数据相关的几个点: q价格控制(Price Control): 决定物料计价方式. S 标准价格(Standar ...