# H2 Database Engine Cheat Sheet

## Downloads

Windows Installer - Zip - Jar

## Using H2

- Add h2*.jar to the classpath (the only dependency is Java 1.4 or newer)
- JDBC driver class: `org.h2.Driver`
- Database URL: `jdbc:h2:~/test`
- A new database is automatically created if it does not exist
- Closing the last connection closes a database
- H2 is open source, free to use and distribute. See also license.

## Database URL Shortlist

Embedded | jdbc:h2:~/test | 'test' in the current user home directory
jdbc:h2:/data/test | 'test' in the directory /data/
jdbc:h2:test | 'test' in the current working directory
In-Memory | jdbc:h2:mem:test | named; multiple connections within the same process
jdbc:h2:mem: | unnamed private database; only one connections
Server Mode | jdbc:h2:tcp://localhost/~/test | 'test' in the current user home directory
jdbc:h2:tcp://localhost//data/test | 'test' in the directory /data/
Compatibility | jdbc:h2:...;MODE=MySQL | or DB2, Derby, HSQLDB, MSSQLServer, Oracle, PostgreSQL
Debug | jdbc:...;TRACE_LEVEL_FILE=3 | logs JDBC calls to test.trace.db

## H2 Console Tool

Start: double click the h2*.jar file, or run `java -jar h2*.jar`, `h2.bat` or `h2.sh`.

## Maven

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>${version}</version>
    </dependency>

## Hibernate

Use the H2 or the HSQLDB dialect.

## TopLink and Glassfish

Datasource Classname: org.h2.jdbcx.JdbcDataSource
toplink.target-database: oracle.toplink.essentials.platform.database.H2Platform

## Connect using JDBC

    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
    conn.close();

## Connection Pool

    JdbcConnectionPool cp = JdbcConnectionPool.create("jdbc:h2:~/test", "sa", "");
    Connection conn = cp.getConnection(); ... conn.close();
    cp.dispose();

## Start a Server

    java -cp h2*.jar org.h2.tools.Server

## Reference

SQL Grammar (or run 'HELP <command>' in the H2 Console) - Functions - Data Types

## Other Features

Fulltext search - Database Files Encryption - Read Only Databases - Read Only Databases in Zip or Jar File

## Command Line Tools

Backup - ChangeFileEncryption - Console - ConvertTraceFile - CreateCluster - DeleteDbFiles - Recover - Restore - RunScript - Script - Server - Shell

## Reading CSV files

SELECT * FROM CSVREAD('test.csv');