简体   繁体   中英

Connect as user with no password set on Postgresql 8.4 via JDBC

I'm trying to connect to a PostgreSQL 8.4 DB in Ubuntu 10.10 via the JDBC drivers. I'm connecting via jdbc:postgresql:localhost:5433/dbname because PostgreSQL is running on a non-default port 5433 so I have to specify the port.

I've already edited my postgresql.conf to set listen_addresses = "*" . I understand that even though it's localhost, it's still using TCP/IP to connect via JDBC.

My problem is that I created a user without a password. If i do not specify a password with DriverManager.connect(url) , it errors indicating that I need to specify a password for authentication. Every password I try, including empty string, fails to authenticate with the DB.

How can I connect?

Edit: If connecting over wrong port, the error is : PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections. When attempting to connect on the correct port, I'm getting PSQLException: FATAL: password authentication failed for user "user". THis is remedied by the accepted answer below.

If you have pg_hba.conf set to require md5 authentication and the user has no password, then no authentication can occur.

ALTER USER the_user_name PASSWORD 'give_it_a_password';

Alternately, use ident or (for localhost only, unsafe) trust authentication for that user/db combo in pg_hba.conf if you really must have no password. This is usually a bad idea, it's much better to just set a password.

Demo:

$ 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=> 

to connect to your database:

    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!");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM