H2 Database Engine - A very fast, open source, JDBC API database with embedded and server modes, transaction support, multi-version concurrency, browser-based console application, encrypted databases, fulltext search, and pure Java implementation with small footprint
—
H2 provides a comprehensive set of command-line tools and utilities for database administration, maintenance, and data management operations. These tools can be executed from command line, programmatically, or through the H2 Console web interface.
All tool classes extend the base Tool class and can be executed both from command line and programmatically.
Starts H2 database servers (TCP, Web Console, PostgreSQL compatibility).
public class Server extends Tool implements Runnable, ShutdownHandler {
public Server();
public Server(Service service, String... args);
// Main entry point
public static void main(String... args);
// Server management
public Server start() throws SQLException;
public void stop();
public boolean isRunning(boolean traceError);
// Configuration
public String getURL();
public int getPort();
public String getStatus();
}Usage Examples:
// Start TCP server programmatically
Server server = new Server();
server.runTool("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
// Or using constructor
Server tcpServer = Server.createTcpServer("-tcpPort", "9092", "-tcpAllowOthers");
tcpServer.start();
// Start web console
Server webServer = Server.createWebServer("-webPort", "8082");
webServer.start();
// Start PostgreSQL compatibility server
Server pgServer = Server.createPgServer("-pgPort", "5435");
pgServer.start();
// Stop servers
tcpServer.stop();
webServer.stop();
pgServer.stop();Command Line Usage:
# Start TCP server
java -cp h2-*.jar org.h2.tools.Server -tcp -tcpAllowOthers -tcpPort 9092
# Start web console
java -cp h2-*.jar org.h2.tools.Server -web -webAllowOthers -webPort 8082
# Start all servers
java -cp h2-*.jar org.h2.tools.Server -tcp -web -pgStarts H2 Console with GUI support for desktop environments.
public class Console extends Tool implements ShutdownHandler {
public static void main(String... args);
// Console management
public void runTool(String... args) throws SQLException;
}Usage Examples:
// Start console programmatically
Console console = new Console();
console.runTool("-web", "-browser");
// Start without opening browser
Console console = new Console();
console.runTool("-web");Command Line Usage:
# Start console and open browser
java -cp h2-*.jar org.h2.tools.Console
# Start console without browser
java -cp h2-*.jar org.h2.tools.Console -webInteractive command-line SQL shell for executing queries and commands.
public class Shell extends Tool implements Runnable {
public static void main(String... args);
public void runTool(String... args) throws SQLException;
public void setOut(PrintStream out);
public void setErr(PrintStream err);
}Usage Examples:
// Run shell programmatically
Shell shell = new Shell();
shell.runTool("-url", "jdbc:h2:~/test", "-user", "sa");
// Redirect output
PrintStream myOut = new PrintStream(new FileOutputStream("output.txt"));
shell.setOut(myOut);
shell.runTool("-url", "jdbc:h2:~/test", "-user", "sa", "-sql", "SELECT * FROM INFORMATION_SCHEMA.TABLES");Command Line Usage:
# Interactive shell
java -cp h2-*.jar org.h2.tools.Shell -url jdbc:h2:~/test -user sa
# Execute single command
java -cp h2-*.jar org.h2.tools.Shell -url jdbc:h2:~/test -user sa -sql "SELECT COUNT(*) FROM my_table"Creates SQL script dumps of database contents and structure.
public class Script extends Tool {
public static void main(String... args);
public void runTool(String... args) throws SQLException;
}Usage Examples:
// Create script programmatically
Script script = new Script();
script.runTool("-url", "jdbc:h2:~/mydb", "-user", "sa", "-script", "backup.sql");
// Include data and drop statements
script.runTool("-url", "jdbc:h2:~/mydb", "-user", "sa", "-script", "full_backup.sql",
"-options", "compression", "zip", "drop");Command Line Usage:
# Create SQL script
java -cp h2-*.jar org.h2.tools.Script -url jdbc:h2:~/mydb -user sa -script backup.sql
# Create compressed script with data
java -cp h2-*.jar org.h2.tools.Script -url jdbc:h2:~/mydb -user sa -script backup.sql.gz -options compression gzip
# Script structure only (no data)
java -cp h2-*.jar org.h2.tools.Script -url jdbc:h2:~/mydb -user sa -script structure.sql -options nodataExecutes SQL scripts against a database.
public class RunScript extends Tool {
public static void main(String... args);
public void runTool(String... args) throws SQLException;
// Execute script from string
public static void execute(Connection conn, Reader reader) throws SQLException;
public static void execute(String url, String user, String password,
String fileName, String charsetName,
boolean continueOnError) throws SQLException;
}Usage Examples:
// Run script programmatically
RunScript runScript = new RunScript();
runScript.runTool("-url", "jdbc:h2:~/mydb", "-user", "sa", "-script", "backup.sql");
// Run script with error handling
runScript.runTool("-url", "jdbc:h2:~/mydb", "-user", "sa", "-script", "backup.sql",
"-continueOnError");
// Execute from connection
Connection conn = DriverManager.getConnection("jdbc:h2:~/mydb", "sa", "");
Reader reader = new FileReader("script.sql");
RunScript.execute(conn, reader);Command Line Usage:
# Execute SQL script
java -cp h2-*.jar org.h2.tools.RunScript -url jdbc:h2:~/mydb -user sa -script backup.sql
# Continue on errors
java -cp h2-*.jar org.h2.tools.RunScript -url jdbc:h2:~/mydb -user sa -script backup.sql -continueOnError
# Execute from URL
java -cp h2-*.jar org.h2.tools.RunScript -url jdbc:h2:~/mydb -user sa -script http://example.com/script.sqlCreates compressed backup files of databases.
public class Backup extends Tool {
public static void main(String... args);
public void runTool(String... args) throws SQLException;
}Usage Examples:
// Create backup programmatically
Backup backup = new Backup();
backup.runTool("-url", "jdbc:h2:~/mydb", "-user", "sa", "-file", "mydb_backup.zip");
// Create backup with quiet mode
backup.runTool("-url", "jdbc:h2:~/mydb", "-user", "sa", "-file", "mydb_backup.zip", "-quiet");Command Line Usage:
# Create database backup
java -cp h2-*.jar org.h2.tools.Backup -url jdbc:h2:~/mydb -user sa -file mydb_backup.zip
# Backup with custom directory
java -cp h2-*.jar org.h2.tools.Backup -url jdbc:h2:~/mydb -user sa -file /backups/mydb_backup.zipRestores databases from backup files.
public class Restore extends Tool {
public static void main(String... args);
public void runTool(String... args) throws SQLException;
}Usage Examples:
// Restore backup programmatically
Restore restore = new Restore();
restore.runTool("-file", "mydb_backup.zip", "-dir", "~/restored", "-db", "mydb_restored");
// Restore with quiet mode
restore.runTool("-file", "mydb_backup.zip", "-dir", "~/restored", "-db", "mydb_restored", "-quiet");Command Line Usage:
# Restore database backup
java -cp h2-*.jar org.h2.tools.Restore -file mydb_backup.zip -dir ~/restored -db mydb_restored
# Restore to specific directory
java -cp h2-*.jar org.h2.tools.Restore -file /backups/mydb_backup.zip -dir /data -db productionRecovers data from corrupted database files.
public class Recover extends Tool implements DataHandler {
public static void main(String... args);
public void runTool(String... args) throws SQLException;
}Usage Examples:
// Recover corrupted database
Recover recover = new Recover();
recover.runTool("-dir", "~/corrupted_db", "-db", "mydb");
// Recover with trace information
recover.runTool("-dir", "~/corrupted_db", "-db", "mydb", "-trace");Command Line Usage:
# Recover corrupted database
java -cp h2-*.jar org.h2.tools.Recover -dir ~/corrupted_db -db mydb
# Recover with detailed output
java -cp h2-*.jar org.h2.tools.Recover -dir ~/corrupted_db -db mydb -traceUtility to delete database files safely.
public class DeleteDbFiles extends Tool {
public static void main(String... args);
public void runTool(String... args) throws SQLException;
public static void execute(String dir, String db, boolean quiet) throws SQLException;
}Usage Examples:
// Delete database files programmatically
DeleteDbFiles deleteFiles = new DeleteDbFiles();
deleteFiles.runTool("-dir", "~/mydb", "-db", "test", "-quiet");
// Using static method
DeleteDbFiles.execute("~/mydb", "test", false);Command Line Usage:
# Delete database files
java -cp h2-*.jar org.h2.tools.DeleteDbFiles -dir ~/mydb -db test
# Delete quietly (no confirmation)
java -cp h2-*.jar org.h2.tools.DeleteDbFiles -dir ~/mydb -db test -quietChanges file encryption settings for existing databases.
public class ChangeFileEncryption extends Tool {
public static void main(String... args);
public void runTool(String... args) throws SQLException;
}Usage Examples:
// Change encryption programmatically
ChangeFileEncryption encrypt = new ChangeFileEncryption();
encrypt.runTool("-dir", "~/mydb", "-db", "test", "-cipher", "AES", "-decrypt", "oldpass", "-encrypt", "newpass");Command Line Usage:
# Add encryption to existing database
java -cp h2-*.jar org.h2.tools.ChangeFileEncryption -dir ~/mydb -db test -cipher AES -encrypt newpassword
# Change encryption password
java -cp h2-*.jar org.h2.tools.ChangeFileEncryption -dir ~/mydb -db test -cipher AES -decrypt oldpass -encrypt newpass
# Remove encryption
java -cp h2-*.jar org.h2.tools.ChangeFileEncryption -dir ~/mydb -db test -cipher AES -decrypt passwordCSV import/export functionality for data exchange.
public class Csv implements SimpleRowSource {
// Reading CSV
public static Csv getInstance(String fileName, String[] colNames, String charset);
public static ResultSet read(String fileName, String[] colNames, String charset) throws SQLException;
// Writing CSV
public static int write(String fileName, ResultSet rs, String charset) throws SQLException;
public static void write(String fileName, ResultSet rs, String options) throws SQLException;
// Row source interface
public Object[] readRow() throws SQLException;
public void close();
public void reset() throws SQLException;
}Usage Examples:
// Import CSV data
ResultSet rs = Csv.read("data.csv", null, "UTF-8");
// Process ResultSet...
// Export to CSV
Connection conn = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
Csv.write("customers_export.csv", rs, "UTF-8");
// Custom CSV reading with column names
String[] columns = {"id", "name", "email", "created_date"};
Csv csv = Csv.getInstance("customers.csv", columns, "UTF-8");
Object[] row;
while ((row = csv.readRow()) != null) {
// Process row data
System.out.println("ID: " + row[0] + ", Name: " + row[1]);
}
csv.close();In-memory ResultSet implementation for tools and utilities.
public class SimpleResultSet implements ResultSet, ResultSetMetaData {
public SimpleResultSet();
public SimpleResultSet(SimpleRowSource source);
// Column definition
public void addColumn(String name, int sqlType, int precision, int scale);
public void addColumn(String name);
// Row manipulation
public void addRow(Object... values);
public Object[] readRow() throws SQLException;
// Standard ResultSet methods
public boolean next() throws SQLException;
public String getString(int columnIndex) throws SQLException;
public String getString(String columnLabel) throws SQLException;
public int getInt(int columnIndex) throws SQLException;
// ... other standard ResultSet methods
}Usage Examples:
// Create in-memory result set
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("id", Types.INTEGER, 10, 0);
rs.addColumn("name", Types.VARCHAR, 255, 0);
rs.addColumn("active", Types.BOOLEAN, 1, 0);
// Add data rows
rs.addRow(1, "Alice", true);
rs.addRow(2, "Bob", false);
rs.addRow(3, "Charlie", true);
// Process like normal ResultSet
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
boolean active = rs.getBoolean("active");
System.out.println(id + ": " + name + " (active: " + active + ")");
}File compression utilities for database files and backups.
public class CompressTool {
// Compression methods
public static void compress(String inFileName, String outFileName, String algorithm) throws SQLException;
public static void expand(String inFileName, String outFileName) throws SQLException;
// Available algorithms
public static final String GZIP = "GZIP";
public static final String LZF = "LZF";
public static final String DEFLATE = "DEFLATE";
}Usage Examples:
// Compress file
CompressTool.compress("large_backup.sql", "large_backup.sql.gz", CompressTool.GZIP);
// Decompress file
CompressTool.expand("large_backup.sql.gz", "restored_backup.sql");
// Use with different algorithms
CompressTool.compress("data.sql", "data.sql.lzf", CompressTool.LZF);
CompressTool.compress("data.sql", "data.sql.deflate", CompressTool.DEFLATE);Interface for providing row data to import/export tools.
public interface SimpleRowSource {
Object[] readRow() throws SQLException;
void close();
void reset() throws SQLException;
}Implementation Example:
public class CustomDataSource implements SimpleRowSource {
private List<Object[]> data;
private int currentIndex = 0;
public CustomDataSource(List<Object[]> data) {
this.data = data;
}
@Override
public Object[] readRow() throws SQLException {
if (currentIndex >= data.size()) {
return null; // End of data
}
return data.get(currentIndex++);
}
@Override
public void close() {
// Cleanup resources if needed
}
@Override
public void reset() throws SQLException {
currentIndex = 0;
}
}
// Usage
List<Object[]> myData = Arrays.asList(
new Object[]{1, "Alice", "alice@example.com"},
new Object[]{2, "Bob", "bob@example.com"}
);
SimpleResultSet rs = new SimpleResultSet(new CustomDataSource(myData));public class DatabaseMaintenance {
public void performBackup(String dbUrl, String user, String password, String backupFile) {
try {
Backup backup = new Backup();
backup.runTool("-url", dbUrl, "-user", user, "-password", password, "-file", backupFile);
System.out.println("Backup completed: " + backupFile);
} catch (SQLException e) {
System.err.println("Backup failed: " + e.getMessage());
}
}
public void performRestore(String backupFile, String targetDir, String dbName) {
try {
Restore restore = new Restore();
restore.runTool("-file", backupFile, "-dir", targetDir, "-db", dbName);
System.out.println("Restore completed: " + dbName);
} catch (SQLException e) {
System.err.println("Restore failed: " + e.getMessage());
}
}
public void exportToScript(String dbUrl, String user, String password, String scriptFile) {
try {
Script script = new Script();
script.runTool("-url", dbUrl, "-user", user, "-password", password, "-script", scriptFile);
System.out.println("Script export completed: " + scriptFile);
} catch (SQLException e) {
System.err.println("Script export failed: " + e.getMessage());
}
}
}#!/bin/bash
# Database maintenance script
DB_URL="jdbc:h2:~/production"
DB_USER="sa"
DB_PASSWORD="securepassword"
BACKUP_DIR="/var/backups/h2"
DATE=$(date +%Y%m%d_%H%M%S)
# Create backup
java -cp h2-*.jar org.h2.tools.Backup \
-url "$DB_URL" \
-user "$DB_USER" \
-password "$DB_PASSWORD" \
-file "$BACKUP_DIR/backup_$DATE.zip" \
-quiet
# Create SQL script
java -cp h2-*.jar org.h2.tools.Script \
-url "$DB_URL" \
-user "$DB_USER" \
-password "$DB_PASSWORD" \
-script "$BACKUP_DIR/script_$DATE.sql" \
-options compression gzip
echo "Maintenance completed at $(date)"Install with Tessl CLI
npx tessl i tessl/maven-com-h2database--h2