開発メモ

開発用のメモです。

Java Commons DBUtile 基本

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.junit.Test;

public class DBConnectTest {

    @Test
    public void test() throws Exception {
        Connection connection;

        Class.forName("org.h2.Driver");
        connection = DriverManager.getConnection("jdbc:h2:file:./test");

        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;
            }
        };

        QueryRunner qr = new QueryRunner();
        Object[] rets = qr.query(connection, "SELECT 1", h);
        for (Object ret : rets) {
            System.out.println(ret);
        }
    }
}
Twitter: @asahina_alice