示例代碼來啓動和停止編程的HSQL網絡服務器。爲簡潔起見,刪除了進口。
保持簡單,這段代碼不是線程安全的。這只是示例代碼。
另請注意,內存數據庫將在接收到第一個jdbc請求時自動啓動。另外,通過jdbc執行SQL命令SHUTDOWN來關閉內存數據庫。
使用org.hsqldb.server.WebServer(即hsql數據庫服務器使用http端口80),但您可以改爲使用org.hsqldb.server.Server。您可以調用setPort來覆蓋默認端口。
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;
}
}
鏈接不工作.. – 2015-03-08 03:00:10
該鏈接應該是固定的或最好在這裏發佈的答案。 – skrii 2016-11-03 17:59:48
修復了具有相同內容的另一篇文章的鏈接。 – 2016-11-23 10:43:40