zoukankan      html  css  js  c++  java
  • DbUtils: JDBC Utility Component Examples翻译

    DbUtils:JDBC实用组件实例

    这一页提供了一些展示如何使用DbUtils的示例。

    基本用法

    DbUtils是一个非常小的类库,因此浏览完所有类的javadoc不会花费很长时间。DbUtils的核心类/接口是QueryRunnerResultSetHandler。你不需要知道其它DbUtils类就可以使用这一类库。下面的例子展示了这些类是如何一起使用的。

    // Create a ResultSetHandler implementation to convert the
    // first row into an Object[].
    // 创建一个ResultSetHandler 实现,以把第一行转换成一个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 = 0; i < cols; i++) {
                result[i] = rs.getObject(i + 1);
            }
    
            return result;
        }
    };
    
    // Create a QueryRunner that will use connections from
    // the given DataSource
    // 创建一个QueryRunner,它会使用所给DataSource的连接
    QueryRunner run = new QueryRunner(dataSource);
    
    // Execute the query and get the results back from the handler
    // 执行查询并从handler获取结果
    Object[] result = run.query(
        "SELECT * FROM Person WHERE name=?", h, "John Doe");
    

      

     

    你也可以通过 java.sql.Connection 对象来代替 DataSource来执行先前的操作。注意,在这个例子中,你应该负责关闭Connection 。

     
    ResultSetHandler<Object[]> h = ... // Define a handler the same as above example
    // 定义一个和上面例子一样的handler
    
    // No DataSource so we must handle Connections manually
    // 没有DataSource,所以我们必须手动处理Connections
    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
        // 用result做些什么吧~    
    } finally {
        // Use this helper method so we don't have to check for null
        // 使用DbUtils的方法,所以我们不需要检查是否为null
        DbUtils.close(conn);  
    }
    

      

    你不仅可以从数据库获取数据,你也可以插入或者更新数据。下面的例子将首先插入一个person到数据库,并且之后改变person的height属性。

    QueryRunner run = new QueryRunner( dataSource );
    try
    {
        // Execute the SQL update statement and return the number of
        // inserts that were made
        // 执行SQL更新语句,并返回插入的数量???
        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
        // 处理它
    }
    

       

    对于长时间运行的调用,你可以使用 AsyncQueryRunner异步执行调用。 AsyncQueryRunner 类和 QueryRunner 类调用具有相同的方法;然而,这些方法返回一个Callable.

    ExecutorCompletionService<Integer> executor = new ExecutorCompletionService<Integer>( Executors.newCachedThreadPool() );
    AsyncQueryRunner asyncRun = new AsyncQueryRunner( dataSource );
    
    try
    {
        // Create a Callable for the update call
        // 为update调用创建一个Callable对象
        Callable<Integer> callable = asyncRun.update( "UPDATE Person SET height=? WHERE name=?", 2.05, "John Doe" );
        // Submit the Callable to the executor
        // 向executor提交Callable对象
        executor.submit( callable );
    } catch(SQLException sqle) {
        // Handle it
        // 处理它
    }
    
    // Sometime later (or in another thread)
    // 稍后(或在另一个线程之中)
    try
    {
       // Get the result of the update
       // 获取update的结果
       Integer updates = executor.take().get();
    } catch(InterruptedException ie) {
        // Handle it
        // 处理异常
    }
    

      

    ResultSetHandler的实现

    在上面的例子中,我们实现了 ResultSetHandler 接口以把 ResultSet 第一行数据转换成一个Object[]。这是一个相当通用的实现,它可以在很多项目中重用。为了认识到这一点,DbUtils在org.apache.commons.dbutils.handlers包中提供了一系列 ResultSetHandler 实现,这些实现可以执行通常转换成array,maps,和JavaBean。There is a version of each implementation that converts just the first row and another that converts all rows in the ResultSet.下面是每一个实现的一个版本,这些都只是把第一行转换了,以及转换了在 ResultSet中的所有行。

    我们将以一个例子开始,使用 BeanHandler 从 ResultSet 获取一行并把它转换成一个JavaBean。

    QueryRunner run = new QueryRunner(dataSource);
    
    // Use the BeanHandler implementation to convert the first
    // ResultSet row into a Person JavaBean.
    // 使用BeanHandler实现以把ResultSet中第一行转换成一个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.
    // 执行有一个替代参数的SQL语句,并把返回结果存入由BeanHandler生成的Person对象
    Person p = run.query("SELECT * FROM Person WHERE name=?", h, "John Doe"); 
    

       

    现在我们将使用BeanListHandler从 ResultSet获取所有行,并以JavaBean List 的形式返回。

    QueryRunner run = new QueryRunner(dataSource);
    
    // Use the BeanHandler implementation to convert the first
    // ResultSet row into a Person JavaBean.
    // 使用BeanListHandler实现以把所有的结果集行转换成Person JavaBean列表
    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.
    // 执行SQL语句并返回由BeanListHandler生成的Person对象列表
    List<Person> persons = run.query("SELECT * FROM Person", h);
    

       

    自定义RowProcessor

    每一个所提供的ResultSetHandler 实现接收一个RowProcessor 来做真实的行到对象的转换。通过默认处理器使用BasicRowProcessor 实现,但是你可以实现一个自定义的版本来插入。可能最通用的自定义是去实现toBean() 方法来处理自定义数据库数据类型问题。

    自定义BeanProecssor

    BasicRowProcessor 使用一个BeanProcessor 来把 ResultSet 列转成JavaBean 属性. 你可以子类化并覆盖处理流程来指定你的应用程序的数据类型映射。所提供的实现把数据类型转换委托给JDBC驱动。

    BeanProcessor 把列映射成为bean属性,如在BeanProcessor.toBean() Java文档中所述。 列名必须匹配bean的属性名,且区分大小写。例如,通过调用 setFirstName() 方法,firstname 类可以存储在bean中。然而,很多数据库列明包含或者不能使用或者在Java方法名中不常用的字符。你可以通过以下两种方法之一以把bean属性映射到这些列中。

    1. 把SQL中的列名别名化以使它们和Java属性名匹配: select social_sec# as socialSecurityNumber from person
    2. 子类化BeanProcessor,并覆盖方法mapColumnsToProperties() 来删除违规字符。

    原文

      原文传送门

  • 相关阅读:
    iis出现2145318902错误
    div在父容器中水平垂直居中
    SSRS中错误:为用户“NT AUTHORITY\NETWORK SERVICE”授予的权限不足,无法执行此操作。 (rsAccessDenied)解决方案
    数字签名
    SQL无法连接问题
    DataTable导出到excel中,及乱码问题
    Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its depe
    Windows 7无法启动“bootmgr is compressed”解决办法
    U盘安装xp
    IIS7下浏览网站出现503,应用程序池无法启动.事件查看器中出现"Windows 找不到本地配置文件,正在用临时配置文件让您登录。当您注销时,对此配置文件所作的更改将丢失。"
  • 原文地址:https://www.cnblogs.com/basilguo/p/dbutils_using_example.html
Copyright © 2011-2022 走看看