H2 数据库 isClosed/isValid 报告 "not closed",即使使用虚假凭据

H2 database isClosed/isValid report "not closed", even with bogus credentials

我在内存数据库中构建了一个 H2 用于短期存储。我从一个简短的 Java 存根连接到数据库并进行测试以确保我已成功连接。由于它很短,我已经包含了完整的代码。我同时使用了 .isClosed 和 isValid(0)。 Is closed 总是返回否定(意味着未关闭)并且 isValid(0) 总是以肯定回答(意味着未关闭)。无论我使用有效凭据还是伪造凭据,它们都以这种方式表现

public class H2SeeWhatICabBreak {

public static Connection getConnection()   {
    try {
        Class.forName("org.h2.Driver");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.exit(-1);
    }

    Connection conn = null;
    Properties connectionProps = new Properties();
    connectionProps.put("user", "<username>");
    connectionProps.put("password", "<password>");
    try {
        conn = DriverManager.getConnection("jdbc:h2:~/tickets");
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.exit(-1);
    }

    return conn;
}

public static void main(String[] args) throws SQLException {

        Connection dbCTX = getConnection();

        if (dbCTX == null ) {
            System.err.println("Got back a null, good bye!!");
            System.exit(-1);
        }

        if (dbCTX.isClosed())
        {
            System.err.println("There's something rotten in River City");
        } else {
            System.err.println("Got connection");
        }

        System.err.println("Looks like we did it??");


    }
}

有什么想法吗?

您创建并设置了 connectionProps,但实际上并没有使用。您的代码等效于以下内容。请注意 H2 的默认用户名和密码为空字符串。

conn = DriverManager.getConnection("jdbc:h2:~/tickets");

conn = DriverManager.getConnection("jdbc:h2:~/tickets", "", "");

conn = DriverManager.getConnection("jdbc:h2:~/tickets", null);

conn = DriverManager.getConnection("jdbc:h2:~/tickets", new Properties());

你想要做的是:

conn = DriverManager.getConnection("jdbc:h2:~/tickets", 
    "<username>", "<password>");

或(更复杂):

Properties connectionProps = new Properties();
connectionProps.put("user", "<username>");
connectionProps.put("password", "<password>");
conn = DriverManager.getConnection("jdbc:h2:~/tickets",
    connectionProps);