Connecting to local instance of PostgreSql with JDBC

后端 未结 2 492
-上瘾入骨i
-上瘾入骨i 2021-02-07 03:09

I have a running local instance of PostgreSql on a linux machine. When I use psql command from the shell I success to log in without any problem. I need to connect

相关标签:
2条回答
  • 2021-02-07 03:25

    In addition to other answers note that by default Postgres is configured to accept connections via Unix sockets with authentication based on your operating system account, that's why psql works fine and doesn't require the password.

    JDBC connections are made over TCP/IP with password authentication, so you need to modify pg_hba.conf accordingly. For example, this line allows TCP/IP connections from the same machine to all databases for all users with password authentication:

    host    all         all         127.0.0.1/32          md5
    

    After adding this line jdbc:postgresql:databasename should work.

    EDIT: You can't create a JDBC connection over Unix socket since PostgreSQL JDBC driver can only work over TCP/IP. The password you use when creating JDBC connection is the password assigned to your user. If you don't have it, you can assign it, for example, using ALTER USER command. See 19.3. Authentication methods.

    See also:

    • 19.1. The pg_hba.conf file
    0 讨论(0)
  • 2021-02-07 03:37

    It's all explained in official documentation.

    This is the relevant part:

    String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
    Connection conn = DriverManager.getConnection(url);
    
    0 讨论(0)
提交回复
热议问题