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.io.InputStream;
09: import java.io.InputStreamReader;
10: import java.sql.Connection;
11: import java.sql.DriverManager;
12: import java.sql.ResultSet;
13: import java.sql.Statement;
14:
15: import org.h2.tools.RunScript;
16:
17: /**
18: * In this example a database is initialized from compressed script in a jar
19: * file.
20: */
21: public class InitDatabaseFromJar {
22:
23: public static void main(String[] args) throws Exception {
24: new InitDatabaseFromJar().createScript();
25: new InitDatabaseFromJar().initDb();
26: }
27:
28: /**
29: * Create a script from a new database.
30: */
31: private void createScript() throws Exception {
32: Class.forName("org.h2.Driver");
33: Connection conn = DriverManager
34: .getConnection("jdbc:h2:mem:test");
35: Statement stat = conn.createStatement();
36: stat.execute("CREATE TABLE TEST(NAME VARCHAR)");
37: stat.execute("INSERT INTO TEST VALUES('Hello World')");
38: stat.execute("SCRIPT TO 'script.sql'");
39: conn.close();
40: }
41:
42: /**
43: * Initialize a database from a SQL script file.
44: */
45: void initDb() throws Exception {
46: Class.forName("org.h2.Driver");
47: Connection conn = DriverManager
48: .getConnection("jdbc:h2:mem:test");
49: InputStream in = getClass().getResourceAsStream("script.sql");
50: if (in == null) {
51: System.out
52: .println("Please add the file script.sql to the classpath, package "
53: + getClass().getPackage().getName());
54: } else {
55: RunScript.execute(conn, new InputStreamReader(in));
56: ResultSet rs = conn.createStatement().executeQuery(
57: "SELECT * FROM TEST");
58: while (rs.next()) {
59: System.out.println(rs.getString(1));
60: }
61: conn.close();
62: }
63: }
64: }
|