Search code examples
javah2h2db

h2 doesn't start programmatically


I have wrote following code:

  private static void startH2(){
        Server server = null;
        try {
            server = Server.createTcpServer("-tcpAllowOthers").start();
            Class.forName("org.h2.Driver");
            Connection conn = DriverManager.
                    getConnection("jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL", "sa", "");
        } catch (Exception e) {
            LOG.error("Error while initialize", e);
        }
        System.out.println("finish");
    }
    public static void main(String [] args){
        startH2();
    }

I run my main method and see following situation:

enter image description here

Looks like Server.createTcpServer creates new non daemon thread.

but by url localhost:8082 I don't see h2 web console(actual result - ERR_CONNECTION_REFUSED)

How to fix this?

P.S.

I have noticed that by url

http://localhost:9092/

my browser downlods file with strange content:

enter image description here

if to decode this text I see following message:

Version mismatch, driver version is “0” but server version is “15”

I use h2 version 1.4.182


Solution

  • H2 contains multiple servers:

    You have started the TCP Server. If you want to use a browser, you also need to start the Web Server:

    private static void startH2(){
        Server tcpServer = null;
        Server webServer = null;
        try {
            tcpServer = Server.createTcpServer("-tcpAllowOthers").start();
            System.out.println("TCP Server Port: " + tcpServer.getPort());
            Class.forName("org.h2.Driver");
            Connection conn = DriverManager.
                    getConnection("jdbc:h2:tcp://localhost/~/test22;MODE=PostgreSQL", "sa", "");
            webServer = Server.createWebServer().start();
            System.out.println("Web Server (H2Console) Port: " + webServer.getPort());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("finish");
    }