H2 Database User Manual
Basic Operations
Create Database
Embedded mode (in-memory):
String url = "jdbc:h2:mem:testdb";
Connection conn = DriverManager.getConnection(url, "sa", "");
File database:
String url = "jdbc:h2:file:./data/testdb";
Connection conn = DriverManager.getConnection(url, "sa", "password");
Create Table
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Insert Data
INSERT INTO users (name, email) VALUES ('John', '[email protected]');
INSERT INTO users (name, email) VALUES ('Jane', '[email protected]');
Query Data
SELECT * FROM users;
SELECT * FROM users WHERE name = 'John';
SELECT COUNT(*) FROM users;
Update Data
UPDATE users SET email = '[email protected]' WHERE id = 1;
Delete Data
DELETE FROM users WHERE id = 2;
Java Code Examples
Complete JDBC Example
import java.sql.*;
public class H2Example {
public static void main(String[] args) throws Exception {
// Load driver
Class.forName("org.h2.Driver");
// Connect to database
String url = "jdbc:h2:mem:testdb";
Connection conn = DriverManager.getConnection(url, "sa", "");
// Create table
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100))");
// Insert data
stmt.execute("INSERT INTO users (name) VALUES ('John')");
stmt.execute("INSERT INTO users (name) VALUES ('Jane')");
// Query data
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getInt("id") + ": " + rs.getString("name"));
}
// Close connection
rs.close();
stmt.close();
conn.close();
}
}
Using PreparedStatement
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (name, email) VALUES (?, ?)");
pstmt.setString(1, "Bob");
pstmt.setString(2, "[email protected]");
pstmt.executeUpdate();
pstmt.close();
Using Transactions
conn.setAutoCommit(false);
try {
Statement stmt = conn.createStatement();
stmt.execute("INSERT INTO users (name) VALUES ('Alice')");
stmt.execute("INSERT INTO users (name) VALUES ('Charlie')");
conn.commit();
} catch (Exception e) {
conn.rollback();
} finally {
conn.setAutoCommit(true);
}
Advanced Features
Database Mode Switching
H2 can simulate other databases' SQL syntax:
// MySQL mode
String url = "jdbc:h2:mem:testdb;MODE=MySQL";
// PostgreSQL mode
String url = "jdbc:h2:mem:testdb;MODE=PostgreSQL";
// Oracle mode
String url = "jdbc:h2:mem:testdb;MODE=Oracle";
Database Encryption
// Use encrypted database
String url = "jdbc:h2:file:./data/encrypted;CIPHER=AES";
Connection conn = DriverManager.getConnection(url, "sa", "password");
Trace Function
// Enable SQL trace
String url = "jdbc:h2:mem:testdb;TRACE_LEVEL_FILE=3";
Start TCP Server
import org.h2.tools.Server;
Server server = Server.createTcpServer().start();
System.out.println("H2 TCP Server started: " + server.getURL());
Using H2 Console
Start H2 Web Console:
java -jar h2.jar -web
Then open in browser: http://localhost:8082
Common SQL Statements
Data Types
H2 supports multiple data types:
- Integer types: INT, INTEGER, BIGINT, SMALLINT, TINYINT
- Floating point types: FLOAT, REAL, DOUBLE, DECIMAL
- String types: VARCHAR, CHAR, CLOB
- Date/Time types: DATE, TIME, TIMESTAMP
- Boolean type: BOOLEAN
- Binary types: BLOB, BINARY
Index Operations
Create index:
CREATE INDEX idx_name ON users(name);
Drop index:
DROP INDEX idx_name;
Constraint Operations
Add primary key:
ALTER TABLE users ADD PRIMARY KEY (id);
Add foreign key:
ALTER TABLE orders ADD FOREIGN KEY (user_id) REFERENCES users(id);
View Table Structure
DESCRIBE users;
-- or
SHOW COLUMNS FROM users;
View All Tables
SHOW TABLES;
Performance Optimization
Batch Operations
Use batch operations to improve performance:
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (name) VALUES (?)");
for (int i = 0; i < 1000; i++) {
pstmt.setString(1, "User" + i);
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
Connection Pool
In production environments, it is recommended to use a connection pool like HikariCP:
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:h2:file:./data/testdb");
config.setUsername("sa");
config.setPassword("");
config.setMaximumPoolSize(10);
HikariDataSource ds = new HikariDataSource(config);
Backup and Recovery
Backup Database
SCRIPT TO 'backup.sql';
Restore Database
RUNSCRIPT FROM 'backup.sql';
Common Error Handling
Database File Locked
Ensure no other connections are using the database file. H2 supports concurrent reads, but writes require exclusive access.
In-Memory Database Data Lost
In-memory database (jdbc:h2:mem:) data will be lost after all connections close. For persistence, use file database mode.
Class Not Found
Ensure org.h2.Driver class is in the classpath.
