2011年10月19日水曜日

[Servlet][JSP][DAO]JDBCについて(可変引数のないSELECT)

DAOクラスでJDBCによるアクセスを行う場合は、まずJDBCドライバをクラスパスに配置する。
MySQLならばWebサイトに行ってjarをダウンロードしてくると、JDBCを使えるようになる。

eclipseで開発しているなら、WEB-INF/lib配下にJDBCのjarを置き、ビルドパスに追加する。
DBにアクセスするコードは、次のようになる。

// SELECTの実行
public void executeSelect() throws ClassNotFoundException, SQLException {

    Connection conn = null;
    Statement s = null;
    ResultSet rs = null;
    try {
        // JDBCドライバをクラス名で探し、初期化を行う
        Class.forName("com.mysql.jdbc.Driver");

        // コネクションを取得する
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/SAMPLE",
                "sampleuser", "samplepassword");

        // ステートメントを作成する
        s = conn.createStatement();

        // SQLを実行し、リザルトセットを得る
        rs = s.executeQuery("SELECT * FROM SAMPLE_TABLE");

        // テーブルにintのID、varcharの文字列がある場合、次のように取得できる
        while (rs.next()) {
            Integer id = rs.getInt(1);
            String str = rs.getString(2);
            System.out.println("ID : " + id);
            System.out.println("STR : " + str);
        }

    } finally {

        // 後始末をする
        if (conn != null) {
            conn.close();
        }
        if (s != null) {
            s.close();
        }
        if (rs != null) {
            rs.close();
        }
    }
}

0 件のコメント:

コメントを投稿