Java PostgreSQL:连接失败时抑制错误输出

时间:2018-06-25 13:57:37

标签: postgresql jdbc

我正在使用Java连接到PostgreSQL数据库。

用户在命令行中输入用户名和密码,然后测试连接。我在其周围放了一个try-catch块,但是当连接失败时,它仍会打印一条错误消息。我不希望用户看到此消息,我只想自己处理错误,通常可以通过try-catch构造来实现。但是,在这种特殊情况下,无论如何都会打印该消息。如何在此处隐藏该消息?

相关代码:

import java.sql.*;

public class ChessDatabase {

    private Connection chessDB;
    private String username;
    private String password;

    ChessDatabase(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public boolean isConnected() {
        try {
            chessDB = DriverManager.getConnection("jdbc:postgresql://[...]", username, password);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}

错误消息:

Jun 25, 2018 3:38:24 PM org.postgresql.core.v3.ConnectionFactoryImpl log
WARNING: SQLException occurred while connecting to [...]
org.postgresql.util.PSQLException: FATAL: PAM authentication failed for user "[...]"
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:473)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:205)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
    at ChessDatabase.isConnected(ChessDatabase.java:35)
    [...]
Jun 25, 2018 3:38:24 PM org.postgresql.Driver connect
SEVERE: Connection error: 
org.postgresql.util.PSQLException: FATAL: PAM authentication failed for user "[...]"
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:473)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:205)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
    at org.postgresql.Driver.makeConnection(Driver.java:452)
    at org.postgresql.Driver.connect(Driver.java:254)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
    at ChessDatabase.isConnected(ChessDatabase.java:35)
    [...]

PS:仅作说明,如果用户名和密码正确,则连接有效,并且不会打印错误消息。因此,问题并没有消除错误,而不仅仅是消息。

1 个答案:

答案 0 :(得分:2)

借助JB Nizet提供的链接,我发现可以将"?loggerLevel=OFF"附加到DriverManager.getConnection()中的第一个参数上。这样消息就不会被打印出来。