| 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.Statement; |
| 11 |
import org.h2.store.fs.FileUtils; |
| 12 |
import org.h2.tools.Backup; |
| 13 |
import org.h2.tools.DeleteDbFiles; |
| 14 |
|
| 15 |
/** |
| 16 |
* This sample application shows how to create and use a read-only database in a |
| 17 |
* zip file. The database file is split into multiple smaller files, to speed up |
| 18 |
* random-access. Splitting up the file is only needed if the database file is |
| 19 |
* larger than a few megabytes. |
| 20 |
*/ |
| 21 |
public class ReadOnlyDatabaseInZip { |
| 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 |
|
| 32 |
// delete all files in this directory |
| 33 |
FileUtils.deleteRecursive("~/temp", false); |
| 34 |
|
| 35 |
Connection conn; |
| 36 |
Class.forName("org.h2.Driver"); |
| 37 |
|
| 38 |
// create a database where the database file is split into |
| 39 |
// multiple small files, 4 MB each (2^22). The larger the |
| 40 |
// parts, the faster opening the database, but also the |
| 41 |
// more files. 4 MB seems to be a good compromise, so |
| 42 |
// the prefix split:22: is used, which means each part is |
| 43 |
// 2^22 bytes long |
| 44 |
conn = DriverManager.getConnection( |
| 45 |
"jdbc:h2:split:22:~/temp/test"); |
| 46 |
|
| 47 |
System.out.println("adding test data..."); |
| 48 |
Statement stat = conn.createStatement(); |
| 49 |
stat.execute( |
| 50 |
"create table test(id int primary key, name varchar) " + |
| 51 |
"as select x, space(1000) from system_range(1, 2000)"); |
| 52 |
|
| 53 |
System.out.println("defrag to reduce random access..."); |
| 54 |
stat.execute("shutdown defrag"); |
| 55 |
conn.close(); |
| 56 |
|
| 57 |
System.out.println("create the zip file..."); |
| 58 |
Backup.execute("~/temp/test.zip", "~/temp", "", true); |
| 59 |
|
| 60 |
// delete the old database files |
| 61 |
DeleteDbFiles.execute("split:~/temp", "test", true); |
| 62 |
|
| 63 |
System.out.println("open the database from the zip file..."); |
| 64 |
conn = DriverManager.getConnection( |
| 65 |
"jdbc:h2:split:zip:~/temp/test.zip!/test"); |
| 66 |
// the database can now be used |
| 67 |
conn.close(); |
| 68 |
} |
| 69 |
|
| 70 |
} |