JMemo017

DBに接続

PostgreSQLの場合

package test;

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

public class Test {

	public static void main(String[] args) {

		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

		try {
			// ドライバクラスをロード
			Class.forName("org.postgresql.Driver");

			// データベースへ接続
			String host = "localhost";
			String db = "db1";
			String user = "user1";
			String pass = "pass1";
			String url = String.format(
					"jdbc:postgresql://%s:5432/%s?user=%s&password=%s", host, db, user, pass);
			conn = DriverManager.getConnection(url);

			// ステートメントオブジェクトを生成
			String sql = "SELECT 1, 'ABC'";
			stmt = conn.prepareStatement(sql);

			// クエリーを実行して結果セットを取得
			rs = stmt.executeQuery();

			// 検索された行数分ループ
			while (rs.next()) {
				int no = rs.getInt(1);
				String msg = rs.getString(2);
				System.out.println(no + " " + msg);
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();

		} catch (SQLException e) {
			e.printStackTrace();

		} finally {
			try {
				if (rs != null) {
					rs.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();

			}

			try {
				if (stmt != null) {
					stmt.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
 
			}
 
			try {
				if (conn != null) {
					conn.close();
				}
 
			} catch (SQLException e) {
				e.printStackTrace();
 
			}

		}

	}

}
最終更新:2011年12月15日 16:26