Javaのお勉強



JDBCでMySQLに接続@Javaのお勉強

JDBCを用いてMySQLに接続します。
http://www.mysql.com/downloads/api-jdbc.htmlでダウンロードできます。

ドライバクラスをロードします。
org.gjt.mm.mysql.Driverです。

接続を行います。
接続文字列は、「"jdbc:mysql://localhost/DBNAME", "ID", "PASS"」です。

Statementを生成し、executeQueryにてSQL文を実行します。
結果は、ResultSetにて取得します。

ResultSetから結果を抜き出して、表示します。


public static void main(String[] args) {

    //java.sql
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    String sqlStr;

    try {
        //ドライバクラスをロードする
        Class.forName("org.gjt.mm.mysql.Driver");

        //MySQLに接続
        con = DriverManager.getConnection("jdbc:mysql://localhost/DBNAME", "ID", "PASS");

        //ステートメント生成
        stmt = con.createStatement();

        //SQL文
        sqlStr = "SELECT * FROM TABLE";

        //SQL文実行
        rs = stmt.executeQuery(sqlStr);

        //検索結果数だけループ
        while(rs.next()){
            //レコードの値
            int id = rs.getInt("ID");
            String name = rs.getString("NAME");

            //表示
            System.out.println(id + ":" + name);
        }

        //クローズ
        rs.close();
        stmt.close();
        con.close();

    } catch (Exception ex) {
        try {
            //クローズ
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (con != null) con.close();
        } catch (Exception e) {
        }
        //エラー
        ex.printStackTrace();
    }
}




Copyright (C) 2008-2026 Javaのお勉強. All Rights Reserved.