| 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.io.InputStream; |
| 9 |
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 |
/** |
| 24 |
* This method is called when executing this sample application from the |
| 25 |
* command line. |
| 26 |
* |
| 27 |
* @param args the command line parameters |
| 28 |
* @throws Exception on failure |
| 29 |
*/ |
| 30 |
public static void main(String... args) throws Exception { |
| 31 |
createScript(); |
| 32 |
new InitDatabaseFromJar().initDb(); |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Create a script from a new database. |
| 37 |
*/ |
| 38 |
private static void createScript() throws Exception { |
| 39 |
Class.forName("org.h2.Driver"); |
| 40 |
Connection conn = DriverManager.getConnection("jdbc:h2:mem:test"); |
| 41 |
Statement stat = conn.createStatement(); |
| 42 |
stat.execute("CREATE TABLE TEST(NAME VARCHAR)"); |
| 43 |
stat.execute("INSERT INTO TEST VALUES('Hello World')"); |
| 44 |
stat.execute("SCRIPT TO 'script.sql'"); |
| 45 |
stat.close(); |
| 46 |
conn.close(); |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Initialize a database from a SQL script file. |
| 51 |
*/ |
| 52 |
void initDb() throws Exception { |
| 53 |
Class.forName("org.h2.Driver"); |
| 54 |
InputStream in = getClass().getResourceAsStream("script.sql"); |
| 55 |
if (in == null) { |
| 56 |
System.out.println("Please add the file script.sql to the classpath, package " |
| 57 |
+ getClass().getPackage().getName()); |
| 58 |
} else { |
| 59 |
Connection conn = DriverManager.getConnection("jdbc:h2:mem:test"); |
| 60 |
RunScript.execute(conn, new InputStreamReader(in)); |
| 61 |
Statement stat = conn.createStatement(); |
| 62 |
ResultSet rs = stat.executeQuery("SELECT * FROM TEST"); |
| 63 |
while (rs.next()) { |
| 64 |
System.out.println(rs.getString(1)); |
| 65 |
} |
| 66 |
rs.close(); |
| 67 |
stat.close(); |
| 68 |
conn.close(); |
| 69 |
} |
| 70 |
} |
| 71 |
} |