【问题标题】:Start H2 database programmatically以编程方式启动 H2 数据库
【发布时间】:2015-05-24 20:44:33
【问题描述】:

我正在用 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

那段代码返回异常:

Feature not supported: "jdbc:h2:tcp://localhost/~/test" [50100-176]

我关注了this article

【问题讨论】:

  • 遗憾的是,您链接的文章不再有效:​​(

标签: java jdbc h2


【解决方案1】:

这样的东西应该可以工作

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();
            }
        

并且输出是连接建立:H2/STACKOVERFLOW

这已经用 h2-1.4.184 测试过

【讨论】:

    【解决方案2】:

    这是我的简单 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();
            }
    
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      我能够更轻松地接受默认设置:

            Server server =  Server.createTcpServer().start();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-14
        • 2017-01-11
        • 2021-07-03
        • 2010-12-02
        • 1970-01-01
        • 2014-11-03
        • 2018-06-26
        相关资源
        最近更新 更多