0

此类通过 h2db 连接到数据库。

   public class DatabaseServer {


    private final String user;
    private final String password;
    private final String database;
    private Connection conn = null;
    private Server webServer = null;
    private Server tcpServer = null;

    public DatabaseServer(String user, String password, String database) {
        this.user = user;
        this.password = password;
        this.database = database;

    }

    public void startServer() throws Exception {
        new Thread(() -> {
            try {
                webServer = Server.createWebServer("-webAllowOthers", "-webPort", "8092");
                webServer.start();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                tcpServer = Server.createTcpServer("-tcpAllowOthers", "-tcpPort", "55756");
                tcpServer.start();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }).start();
        //wait until the servers are created
        while (tcpServer == null || webServer == null) {
            Thread.sleep(40);
        }
    }

错误发生在这里:

public Connection getConnection() throws SQLException {
        String url = "jdbc:h2:" + tcpServer.getURL() + "/~/" + database;
        System.out.println("url: " + url);
        conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

我在服务器模式下有 h2db。用户和密码在构造函数中给出。该代码在我的计算机上运行良好,当我导出到另一台计算机并运行它时,出现此错误:

 org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database "C:/Users/tomas/test" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-202]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:678)
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:477)
    at org.h2.message.DbException.get(DbException.java:223)
    at org.h2.message.DbException.get(DbException.java:199)
    at org.h2.engine.Engine.throwNotFound(Engine.java:189)
    at org.h2.engine.Engine.openSession(Engine.java:72)
    at org.h2.engine.Engine.openSession(Engine.java:222)
    at org.h2.engine.Engine.createSession(Engine.java:201)
    at org.h2.server.TcpServerThread.run(TcpServerThread.java:174)
    at java.base/java.lang.Thread.run(Thread.java:832)
4

1 回答 1

0

在客户端尝试使用数据库之前,必须在服务器端创建数据库。应为在数据库创建期间指定的用户使用安全密码,因为该用户将在数据库中拥有 ADMIN 权限,并且这些权限允许访问数据库本身之外的系统。

H2 不再允许远程数据库创建,因为它会创建远程安全漏洞。

https://h2database.com/html/tutorial.html#creating_new_databases

于 2021-12-17T14:52:18.227 回答