PostgreSQL を外部から接続できるようにして JDBC ドライバ経由で接続する
PostgreSQL を外部から接続できるようにして JDBC ドライバから接続する際のメモ。
PostgreSQL の設定
以下の通りに設定ファイルを編集する。今回はどの IP アドレスからも接続可能な設定にしてます。
■ $POSTGRES_HOME/data/postgresql.conf
#listen_addresses = 'localhost' # what IP address(es) to listen on; listen_addresses = '0.0.0.0' # what IP address(es) to listen on;
■ $POSTGRES_HOME/data/pg_hba.conf
#host all all 127.0.0.1/32 trust host all all 0.0.0.0/0 trust
・接続と認証
https://www.postgresql.jp/document/9.3/html/runtime-config-connection.html
・pg_hba.confファイル
https://www.postgresql.jp/document/9.3/html/auth-pg-hba-conf.html
データベース接続のコード
例外処理等、全部無視してます...
package test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Test { public static void main(String[] args) throws Exception { String url = "jdbc:postgresql://***.***.***.***/testdb"; String user = "postgres"; String password = "postgres"; Connection con; Statement st; ResultSet rs; con = DriverManager.getConnection(url, user, password); st = con.createStatement(); rs = st.executeQuery("select * from t1"); while(rs.next()) { System.out.println(rs.getInt("n")); } } }
※ JDBC ドライバのダウンロード先
・PostgreSQL JDBC Download
https://jdbc.postgresql.org/download.html
[ 環境情報 ]
データベースサーバ
CentOS 6.2
PostgreSQL 9.3.5
クライアント
Windows 7 SP1
Java SE 8 Update 25
postgresql-9.3-1103.jdbc41.jar