Start H2 database programmatically

I was able to do it a little more easily accepting the defaults:

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

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

This has been tested with h2-1.4.184


This is my simple H2-DBManager - just name its filename DBManager.java and feel free to reuse it:

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

    }

}

Tags:

Java

Jdbc

H2