通过JDBC在Postgresql 8.4上设置没有密码的用户连接

时间:2012-11-13 22:03:24

标签: java linux postgresql jdbc

我正在尝试通过JDBC驱动程序连接到Ubuntu 10.10中的PostgreSQL 8.4数据库。我通过jdbc:postgresql:localhost:5433/dbname连接,因为PostgreSQL在非默认端口5433上运行,所以我必须指定端口。

我已经编辑了postgresql.conf来设置listen_addresses = "*"。我知道即使它是localhost,它仍然使用TCP / IP通过JDBC进行连接。

我的问题是我创建了一个没有密码的用户。如果我没有使用DriverManager.connect(url)指定密码,则会出现错误,指示我需要为身份验证指定密码。我尝试的每个密码,包括空字符串,都无法通过DB进行身份验证。

我如何连接?

编辑: 如果连接错误的端口,则错误为:PSQLException:连接被拒绝。检查主机名和端口是否正确以及postmaster是否接受TCP / IP连接。当尝试连接正确的端口时,我收到PSQLException:FATAL:用户“user”的密码验证失败。这可以通过下面接受的答案来解决。

2 个答案:

答案 0 :(得分:10)

如果pg_hba.conf设置为要求md5身份验证且用户没有密码,则不会进行身份验证。

ALTER USER the_user_name PASSWORD 'give_it_a_password';

或者,如果您确实没有密码,请在ident中对该用户/ db组合使用trust或(仅限localhost,不安全)pg_hba.conf身份验证。这通常是一个坏主意,只需设置一个密码就好了。

演示:

$ psql -q -U postgres postgres
postgres=# CREATE USER nopw;
CREATE ROLE

$ psql -h localhost -U nopw postgres
Password for user nopw:               [pressed enter]
psql: fe_sendauth: no password supplied

$ psql -q -U postgres postgres
postgres=# ALTER USER nopw PASSWORD 'test';
postgres=# \q

$ psql -q -h localhost -U nopw postgres
Password for user nopw:            [entered 'test' then pressed enter]
postgres=> 

答案 1 :(得分:1)

连接到您的数据库:

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

    private final String url = "jdbc:postgresql://localhost:5432/dbname";
    private final String driver = "org.postgresql.Driver";
    private final String login = "username";
    private final String password = "";
        private Connection connection = null;
    //...
    try {
    Class.forName(driver);
        connection = DriverManager.getConnection(url,
                login, password);
    } catch (SQLException e) {
        System.out.print(" Unable set the connection!");
    } catch (ClassNotFoundException e) {
        System.out.print(" Unable to load the driver class!");
    }