• 开发
    • 修改 PostgreSQL 的连接配置
    • JDBC连接程序

    开发

    修改 PostgreSQL 的连接配置

    • 修改 PostgreSQL 的监听地址

    编辑 /opt/postgresql/data/postgresql.conf 文件,将

    1. listen_addresses = 'localhost'

    改为:

    1. listen_addresses = '0.0.0.0'
    • 修改信任的机器列表

    编辑 /opt/postgresql/data/pg_hba.conf 文件,将

    1. # IPv4 local connections:
    2. host all all 127.0.0.1/32 trust

    改为:

    1. # IPv4 local connections:
    2. host all all 127.0.0.1/32 trust
    3. host all all 0.0.0.0/0 trust
    • 重启 PostgreSQL
    1. $ bin/pg_ctl stop -s -D pg_data/ -m fast
    2. $ bin/postgres -D pg_data/ >> logfile 2>&1 &

    JDBC连接程序

    1. package com.sequoiadb.sample;
    2. import java.sql.*;
    3.  
    4. public class postgresql_sample {
    5. static{
    6. try {
    7. Class.forName("org.postgresql.Driver");
    8. } catch (ClassNotFoundException e) {
    9. e.printStackTrace();
    10. }
    11. }
    12. public static void main( String[] args ) throws SQLException{
    13. String pghost = "192.168.30.182";
    14. String port = "5432";
    15. String databaseName = "foo";
    16. // postgresql process is running in which user
    17. String pgUser = "sdbadmin";
    18. String url = "jdbc:postgresql://"+pghost+":"+port+"/" + databaseName;
    19. Connection conn = DriverManager.getConnection(url, pgUser, null);
    20. Statement stmt = conn.createStatement();
    21. String sql = "select * from sdb_upcase_field ";
    22. ResultSet rs = stmt.executeQuery(sql);
    23. boolean isHeaderPrint = false;
    24. while (rs.next()) {
    25. ResultSetMetaData md = rs.getMetaData();
    26. int col_num = md.getColumnCount();
    27. if (!isHeaderPrint){
    28. for (int i = 1; i <= col_num; i++) {
    29. System.out.print(md.getColumnName(i) + "|");
    30. isHeaderPrint = true;
    31. }
    32. }
    33. for (int i = 1; i <= col_num; i++) {
    34. System.out.print(rs.getString(i) + "|");
    35. }
    36. System.out.println();
    37. }
    38. stmt.close();
    39. conn.close();
    40. }
    41. }