HSQLDB issue: Starting the HSQL database from Java Code

寵の児 提交于 2019-12-01 01:34:28

Sample code to start and stop the HSQL WebServer programmatically. Imports removed for brevity.

Keeping it simple, this code is not threadsafe. This is just sample code.

Also note that the in memory db will start automatically when it receives the first jdbc request. Also, shutdown the in memory db by executing the SQL command SHUTDOWN via jdbc.

Uses org.hsqldb.server.WebServer (i.e. the hsql db server uses http port 80), but you may use org.hsqldb.server.Server instead. You may call setPort on either to override the default port.

public class HsqlServer {

    /**
     * Start the hsql server locally, with an HTTP interface. Rightclick on this
     * class in Eclipse, and run.
     * 
     * @param args
     */

    private static WebServer ws;

    public static void main(String args[]) {
        new HsqlServer().startDB();
    }

    public void stopDB() {
        if (ws != null) {
            try {
                ws.checkRunning(true);
                System.out.println("db is running. stopping now");
                stopServer2();
            }
            catch(HsqlException hsqle) {
                System.out.println("db is already stopped");
            }
        }
        else {
            System.out.println("DB not started. it is null");
        }
    }

    private void stopServer2() {
        ws.shutdownWithCatalogs(Database.CLOSEMODE_NORMAL);
    }

    public void startDB() {
        // String[] argsToServer = { "--database.0",
        // "file:" + HsqlServerConst.dbFileName, "-dbname.0",
        // HsqlServerConst.dbName };
        // WebServer.main(argsToServer);

        if (ws != null) {
            try {
                ws.checkRunning(false);
                System.out.println("check running is false");
                startServer2();
            } catch (HsqlException hsqle) {
                // already running.
                System.out.println("Server is already running.");
                return;
            }
        } else {
            // start the server, it is null
            System.out.println("server is null, starting now");
            startServer2();
        }
    }

    private WebServer startServer2() {
        ws = new WebServer();
        ws.setDatabasePath(0, "file:" + HsqlServerConst.dbFileName);
        ws.setDatabaseName(0, HsqlServerConst.dbName);
        ws.start();
        return ws;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!