此类通过 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)