| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.samples; |
| 7 |
|
| 8 |
import java.sql.Connection; |
| 9 |
import java.sql.DriverManager; |
| 10 |
import java.sql.SQLException; |
| 11 |
import java.sql.Statement; |
| 12 |
import org.h2.tools.Server; |
| 13 |
|
| 14 |
/** |
| 15 |
* This sample program opens the same database once in embedded mode, |
| 16 |
* and once in the server mode. The embedded mode is faster, but only |
| 17 |
* the server mode supports remote connections. |
| 18 |
*/ |
| 19 |
public class MixedMode { |
| 20 |
|
| 21 |
/** |
| 22 |
* This method is called when executing this sample application from the |
| 23 |
* command line. |
| 24 |
* |
| 25 |
* @param args the command line parameters |
| 26 |
* @throws Exception on failure |
| 27 |
*/ |
| 28 |
public static void main(String... args) throws Exception { |
| 29 |
|
| 30 |
// start the server, allows to access the database remotely |
| 31 |
Server server = Server.createTcpServer("-tcpPort", "9081"); |
| 32 |
server.start(); |
| 33 |
System.out.println( |
| 34 |
"You can access the database remotely now, using the URL:"); |
| 35 |
System.out.println( |
| 36 |
"jdbc:h2:tcp://localhost:9081/~/test (user: sa, password: sa)"); |
| 37 |
|
| 38 |
// now use the database in your application in embedded mode |
| 39 |
Class.forName("org.h2.Driver"); |
| 40 |
Connection conn = DriverManager.getConnection( |
| 41 |
"jdbc:h2:~/test", "sa", "sa"); |
| 42 |
|
| 43 |
// some simple 'business usage' |
| 44 |
Statement stat = conn.createStatement(); |
| 45 |
stat.execute("DROP TABLE TIMER IF EXISTS"); |
| 46 |
stat.execute("CREATE TABLE TIMER(ID INT PRIMARY KEY, TIME VARCHAR)"); |
| 47 |
System.out.println("Execute this a few times: " + |
| 48 |
"SELECT TIME FROM TIMER"); |
| 49 |
System.out.println("To stop this application " + |
| 50 |
"(and the server), run: DROP TABLE TIMER"); |
| 51 |
try { |
| 52 |
while (true) { |
| 53 |
// runs forever, except if you drop the table remotely |
| 54 |
stat.execute("MERGE INTO TIMER VALUES(1, LOCALTIME)"); |
| 55 |
Thread.sleep(1000); |
| 56 |
} |
| 57 |
} catch (SQLException e) { |
| 58 |
System.out.println("Error: " + e.toString()); |
| 59 |
} |
| 60 |
conn.close(); |
| 61 |
|
| 62 |
// stop the server |
| 63 |
server.stop(); |
| 64 |
} |
| 65 |
} |