01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (license2)
04: * Initial Developer: H2 Group
05: */
06: package org.h2.samples;
07:
08: import java.sql.Connection;
09: 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: public static void main(String[] args) throws Exception {
22:
23: // start the server, allows to access the database remotly
24: Server server = Server.createTcpServer(new String[] {
25: "-tcpPort", "9081" });
26: server.start();
27: System.out
28: .println("You can access the database remotely now, using the URL:");
29: System.out
30: .println("jdbc:h2:tcp://localhost:9081/~/test (user: sa, password: sa)");
31:
32: // now use the database in your application in embedded mode
33: Class.forName("org.h2.Driver");
34: Connection conn = DriverManager.getConnection("jdbc:h2:~/test",
35: "sa", "sa");
36:
37: // some simple 'business usage'
38: Statement stat = conn.createStatement();
39: stat.execute("DROP TABLE TIMER IF EXISTS");
40: stat
41: .execute("CREATE TABLE TIMER(ID INT PRIMARY KEY, TIME VARCHAR)");
42: System.out
43: .println("Execute this a few times: SELECT TIME FROM TIMER");
44: System.out
45: .println("To stop this application (and the server), run: DROP TABLE TIMER");
46: try {
47: while (true) {
48: // runs forever, except if you drop the table remotely
49: stat.execute("MERGE INTO TIMER VALUES(1, NOW())");
50: Thread.sleep(1000);
51: }
52: } catch (SQLException e) {
53: System.out.println("Error: " + e.toString());
54: }
55: conn.close();
56:
57: // stop the server
58: server.stop();
59: }
60: }
|