我正在使用Java编写服务器 - 客户端应用程序,我需要在服务器端实现本地数据库,我决定使用H2数据库引擎.
还有一件事是我通过TCP连接来启动和运行数据库.这是我到目前为止所放在一起的:
Class.forName("org.h2.Driver");
Server server = Server.createTcpServer(DB_PATH).start();
Connection currentConn = DriverManager.getConnection(DB_PATH, DB_USER, DB_PASSWORD);
Run Code Online (Sandbox Code Playgroud)
连接字符串的位置jdbc:h2:tcp://localhost/~/test.
这段代码返回一个例外:
Feature not supported: "jdbc:h2:tcp://localhost/~/test" [50100-176]
Run Code Online (Sandbox Code Playgroud)
我跟着这篇文章.
Uel*_*ter 14
这样的事情应该有效
Server server = null;
try {
server = Server.createTcpServer("-tcpAllowOthers").start();
Class.forName("org.h2.Driver");
Connection conn = DriverManager.
getConnection("jdbc:h2:tcp://localhost/~/stackoverflow", "sa", "");
System.out.println("Connection Established: "
+ conn.getMetaData().getDatabaseProductName() + "/" + conn.getCatalog());
} catch (Exception e) {
e.printStackTrace();
Run Code Online (Sandbox Code Playgroud)
输出为Connection Established:H2/STACKOVERFLOW
这已通过h2-1.4.184测试
这是我简单的H2-DBManager - 只需将其文件名命名为DBManager.java,并随意重复使用它:
import java.sql.SQLException;
import org.h2.tools.Server;
public class DBManager {
private static void startDB() throws SQLException {
Server.createTcpServer("-tcpPort", "9092", "-tcpAllowOthers").start();
}
private static void stopDB() throws SQLException {
Server.shutdownTcpServer("tcp://localhost:9092", "", true, true);
}
public static void main(String[] args) {
try {
Class.forName("org.h2.Driver");
if (args.length > 0) {
if (args[0].trim().equalsIgnoreCase("start")) {
startDB();
}
if (args[0].trim().equalsIgnoreCase("stop")) {
stopDB();
}
} else {
System.err
.println("Please provide one of following arguments: \n\t\tstart\n\t\tstop");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
我能够更轻松地接受默认值:
Server server = Server.createTcpServer().start();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11421 次 |
| 最近记录: |