Eclipse で PostgreSQL に接続します。
ドライバのインストール
スタートメニューから PostgreSQL 9.3 →Application Stack Builder
スタックビルダが起動しますので、
「PostgreSQL ~(略)」を選択して「次へ」
「Database Drivers」→「pgJDBC~(略)」にチェックして「次へ」
後は全部そのまま進めてインストールします。
C:Program Files (x86)PostgreSQLpgJDBCpostgresql-9.3-1100.jdbc4.jar
を
Eclipse の実行環境の lib フォルダ
C:pleiadestomcat7lib
にコピーします。
接続設定のコンテキストの作成
PostgreSQL に接続するプロジェクトに接続設定のコンテキストを追加します。
プロジェクトの WebContent/META-INF フォルダを右クリックして、新規→ファイル
context.xml
を追加してください。
内容は以下のようにします。
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/datasource" auth="Container" type="javax.sql.DataSource" driverClassName="org.postgresql.Driver" url="jdbc:postgresql:(DB名)" username="(DBアカウント)" password="(パスワード)" /> </Context>
プログラム
プログラムは以下のようにします。
サーブレットの doGET で実行する内容です。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// データソースの取得
DataSource ds = null;
try {
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
} catch (NamingException e) {
e.printStackTrace();
}
try {
// データベースとの接続
Connection con = ds.getConnection();
// SQL実行
Statement stmt = con.createStatement ();
String sql = "SELECT 1234 AS NUM";
ResultSet rs = stmt.executeQuery (sql);
// SQL結果を出力
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
while(rs.next()){
out.println("NUM:" + rs.getInt("NUM"));
}
out.close();
// データベースのクローズ
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace ();
}
}
「NUM:1234」と表示されれば OK です。