以编程方式启动H2数据库
我正在使用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);
连接字符串是jdbc:h2:tcp://localhost/~/test
。
该段代码返回exception:
Feature not supported: "jdbc:h2:tcp://localhost/~/test" [50100-176]
我跟着这篇文章 。
这样的事情应该有效
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();
输出为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(); } } }
我能够更容易地接受默认值:
Server server = Server.createTcpServer().start();