| 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 |
|
| 13 |
import org.h2.store.fs.FileUtils; |
| 14 |
import org.h2.tools.DeleteDbFiles; |
| 15 |
import org.h2.tools.RunScript; |
| 16 |
import org.h2.tools.Script; |
| 17 |
|
| 18 |
/** |
| 19 |
* This sample application shows how to compact the database files. |
| 20 |
* This is done by creating a SQL script, and then re-creating the database |
| 21 |
* using this script. |
| 22 |
*/ |
| 23 |
public class Compact { |
| 24 |
|
| 25 |
/** |
| 26 |
* This method is called when executing this sample application from the |
| 27 |
* command line. |
| 28 |
* |
| 29 |
* @param args the command line parameters |
| 30 |
* @throws Exception on failure |
| 31 |
*/ |
| 32 |
public static void main(String... args) throws Exception { |
| 33 |
DeleteDbFiles.execute("./data", "test", true); |
| 34 |
Class.forName("org.h2.Driver"); |
| 35 |
Connection conn = DriverManager.getConnection("jdbc:h2:./data/test", "sa", ""); |
| 36 |
Statement stat = conn.createStatement(); |
| 37 |
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)"); |
| 38 |
stat.execute("INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');"); |
| 39 |
stat.close(); |
| 40 |
conn.close(); |
| 41 |
System.out.println("Compacting..."); |
| 42 |
compact("./data", "test", "sa", ""); |
| 43 |
System.out.println("Done."); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Utility method to compact a database. |
| 48 |
* |
| 49 |
* @param dir the directory |
| 50 |
* @param dbName the database name |
| 51 |
* @param user the user name |
| 52 |
* @param password the password |
| 53 |
* @throws SQLException on failure |
| 54 |
*/ |
| 55 |
public static void compact(String dir, String dbName, |
| 56 |
String user, String password) throws SQLException { |
| 57 |
String url = "jdbc:h2:" + dir + "/" + dbName; |
| 58 |
String file = "data/test.sql"; |
| 59 |
Script.process(url, user, password, file, "", ""); |
| 60 |
DeleteDbFiles.execute(dir, dbName, true); |
| 61 |
RunScript.execute(url, user, password, file, null, false); |
| 62 |
FileUtils.delete(file); |
| 63 |
} |
| 64 |
|
| 65 |
} |