java 以编程方式启动 H2 数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29183503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Start H2 database programmatically
提问by fillobotto
I'm coding a server-client application in Java and I need to implement a local database on the server side and I decided to go for H2 database engine.
我正在用 Java 编写一个服务器-客户端应用程序,我需要在服务器端实现一个本地数据库,我决定使用 H2 数据库引擎。
One more thing to add is that I usa TCP connection to start and run the database. This is what I put together so far:
要添加的另一件事是我使用 TCP 连接来启动和运行数据库。这是我到目前为止汇总的内容:
Class.forName("org.h2.Driver");
Server server = Server.createTcpServer(DB_PATH).start();
Connection currentConn = DriverManager.getConnection(DB_PATH, DB_USER, DB_PASSWORD);
Where the connection string is jdbc:h2:tcp://localhost/~/test
.
连接字符串在哪里jdbc:h2:tcp://localhost/~/test
。
That piece of code returns with an exception:
这段代码返回一个异常:
Feature not supported: "jdbc:h2:tcp://localhost/~/test" [50100-176]
I followed this article.
我跟着这篇文章。
回答by Ueli Hofstetter
Something like this should work
这样的事情应该工作
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();
and the output is Connection Established: H2/STACKOVERFLOW
并且输出是连接建立:H2/STACKOVERFLOW
This has been tested with h2-1.4.184
这已经用 h2-1.4.184 测试过
回答by Aydin K.
This is my simple H2-DBManager - just name its filename DBManager.java and feel free to reuse it:
这是我的简单 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();
}
}
}
回答by user6627139
I was able to do it a little more easily accepting the defaults:
我能够更轻松地接受默认值:
Server server = Server.createTcpServer().start();