使用JDBC后无法从h2控制台登录到h2数据库

时间:2015-01-28 07:48:04

标签: java jdbc h2

我找到答案,因为用户名必须从网址What is the default username and password for h2 when there's nothing explicit in JDBC?留空 我也登录了。 但我的问题是为什么我应该使用空白用户名而不是" sa" ??

2 个答案:

答案 0 :(得分:2)

我在Eclipse中所做的不是给出

"jdbc:h2:tcp://localhost/~/test" 

连接网址我已经

"jdbc:h2:tcp://localhost/~/" 

并将db名称设为test。 所以我删除了windows用户文件夹中的test.mv文件。现在一切正常。

答案 1 :(得分:1)

当使用特定用户名创建H2数据库时,无法连接到数据库,使用户名为空,反之亦然。

通过链接中提到的H2版本验证:1.3.161

import java.sql.*;

public class TestH2 {

    public static void main(String[] a) throws Exception {
        try (Connection conn = DriverManager.getConnection("jdbc:h2:./test", "sa", "")) {
            System.out.println(conn);
            String createTable = "CREATE TABLE IF NOT EXISTS TEST_TABLE(ID INT, NAME VARCHAR(255))";
            conn.createStatement().executeUpdate(createTable);
            String insertStmnt = "INSERT INTO TEST_TABLE VALUES(1, 'CAFEBABE');";
            int count = conn.createStatement().executeUpdate(insertStmnt);
            System.out.printf("inserted rows: %d%n", count);
        }

        // will fail with org.h2.jdbc.JdbcSQLException: Wrong user name or password [28000-181]
        try (Connection conn = DriverManager.getConnection("jdbc:h2:./test", "", "")) {
            System.out.println(conn);
            String sql = "SELECT id, name FROM TEST_TABLE";
            ResultSet rs = conn.createStatement().executeQuery(sql);
            while (rs.next()) {
                System.out.printf("id: %d  name: %s%n", rs.getInt("ID"), rs.getString("NAME"));
            }
        }
    }
}