DbUtils を使うとデータベースへのアクセスがJDBCよりラクになる。
いわゆるO/Rマッパー(Hibernateとか?)と比較して、手軽に使えるという利点があるらしい。
設定ファイルが要らない!のがうれしい (DataSource by JNDI とか使わなければ……)。ふつうのアプリから使うのに便利そう。

License は Apache License Version 2.0

入手

まずは、JDBC Utility Component - DbUtils から 最新版 commons-dbutils-1.1.zip をダウンロード。

圧縮ファイルを展開すると、


C:\commons-dbutils-1.1>dir
 
2006/12/27  22:04    <DIR>          .
2006/12/27  22:04    <DIR>          ..
2006/11/28  20:17            33,976 commons-dbutils-1.1.jar
2006/12/27  22:04    <DIR>          docs
2006/11/28  20:17            11,358 LICENSE.txt
2006/11/28  20:17               184 NOTICE.txt
2006/11/28  20:17               231 RELEASE-NOTES.txt
               4 個のファイル              45,749 バイト

とってもシンプル。

コンパイルや実行の際には、commons-dbutils-1.1.jar にクラスパスを通しておけばいい。

MySQL にテスト用のテーブルを用意


create table hogetable (
  id       int          not null auto_increment,
  name     varchar(64)  not null default '',
  hobby    varchar(255) null,
  age      int          not null default 0,
  primary  key          (id)
) ENGINE=MyISAM;

テスト用サンプルコード


import java.sql.*;
import java.util.*;
import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.*;
import org.apache.commons.dbutils.wrappers.*;
 
public class DbUtilsSample {
 
  public static void main(String[] args) throws Exception {
 
    delete();
 
    insert("Alice" , "programming", 53);
    insert("Bob"   , "swimming"   , 25);
    insert("Cathy" , "programming", 92);
    insert("David" ,  null     ,  1);
    insert("Edward", "programming", 12);
 
    select("hobby", "programming");
    select("name" , "Alice");
    select("name" , "David");
  }
 
  private static final String driver   = "com.mysql.jdbc.Driver";
  private static final String url    = "jdbc:mysql://localhost/hogedb";
  private static final String user   = "hogeuser";
  private static final String password = "hogepassword";
 
  private static Connection getConnection() throws Exception {
    Class.forName(driver);
    Connection con = DriverManager.getConnection(url, user, password);
    return con;
  }
 
  private static void delete() throws Exception {
 
    Connection con = getConnection();
 
    QueryRunner qr = new QueryRunner();
 
    int cnt = qr.update(
      con,
      "delete from hogetable"
    );
  }
 
  private static void insert(String p_name, String p_hobby, int age) throws Exception {
 
    Connection con = getConnection();
 
    QueryRunner qr = new QueryRunner();
  
    // QueryRunner#update(
    //   java.sql.Connection conn, <--- The connection to use to run the query.
    //   java.lang.String sql, <--- The SQL to execute.
    //   java.lang.Object[] params); <--- The query replacement parameters.
 
    int cnt = qr.update(
      con,
      "insert into hogetable (name, hobby, age) values (?, ?, ?)",
      new Object[] { p_name, p_hobby, new Integer(age) }
    );
    }
 
  private static void select(String p_key, String p_value) throws Exception {
 
    System.out.println("searching... " + p_key + " = " + p_value);
    
    Connection con = getConnection();
 
    QueryRunner qr = new QueryRunner();
    ResultSetHandler rsh = new MapListHandler();
 
    // java.lang.Object QueryRunner#query(
    //   java.sql.Connection conn, <--- The connection to execute the query in.
    //   java.lang.String sql, <--- The query to execute.
    //   java.lang.Object[] params, <--- The replacement parameters.
    //   ResultSetHandler rsh); <--- The handler that converts the results into an object.
 
    List records = (List)qr.query(
      con,
      "select * from hogetable where " + p_key + " = ?",
      new String[] { p_value },
      rsh
    );
 
    for(Iterator it = records.iterator(); it.hasNext();){
      Map record = (Map)it.next();
      System.out.println("id:"  + record.get("id").getClass() + ":" + record.get("id"));
      System.out.println("name:"  + record.get("name").getClass() + ":" + record.get("name"));
      System.out.println("hobby:" + record.get("hobby").getClass() + ":" + record.get("hobby"));
      System.out.println("age:"   + record.get("age").getClass() + ":" + record.get("age"));
    }
 
    System.out.println();
  }
}

実行結果


searching... hobby = programming
id:class java.lang.Integer:31
name:class java.lang.String:Alice
hobby:class java.lang.String:programming
age:class java.lang.Integer:53
id:class java.lang.Integer:33
name:class java.lang.String:Cathy
hobby:class java.lang.String:programming
age:class java.lang.Integer:92
id:class java.lang.Integer:35
name:class java.lang.String:Edward
hobby:class java.lang.String:programming
age:class java.lang.Integer:12
 
searching... name = Alice
id:class java.lang.Integer:31
name:class java.lang.String:Alice
hobby:class java.lang.String:programming
age:class java.lang.Integer:53
 
searching... name = David
id:class java.lang.Integer:34
name:class java.lang.String:David
Exception in thread "main" java.lang.NullPointerException
    at DbUtilsSample.select(DbUtilsSample.java:92)
    at DbUtilsSample.main(DbUtilsSample.java:22)

select 系では、Map オブジェクトをひとつのレコードとして返してくれる。
カラム名をキーに指定すれば値が取得できてとても簡単。
カラム型とJavaの型がどうやって対応しているかは、よくわからない。
ただ、カラムの値が null のところは、ちゃんと Java の null が返ってきているようだ(NullPointerException 出たし)。

テーブル内のデータ


mysql> select * from hogetable;
+----+--------+-------------+-----+
| id | name   | hobby       | age |
+----+--------+-------------+-----+
| 31 | Alice  | programming |  53 |
| 32 | Bob    | swimming    |  25 |
| 33 | Cathy  | programming |  92 |
| 34 | David  | NULL        |   1 |
| 35 | Edward | programming |  12 |
+----+--------+-------------+-----+
5 rows in set (0.00 sec)

DbUtilsめも には、DbUtils についての多くのサンプルと解説があるので参考になる。

tags: zlashdot Java Java

Posted by NI-Lab. (@nilab)