H2 Database

H2 the Java SQL database. The main features of H2 are:

  • Very fast, open source, JDBC API

  • Embedded and server modes; in-memory databases

  • Browser based Console application

  • Small footprint: around 1.5 MB jar file size

Features

H2 Derby HSQLDB MySQL PostgreSQL
Pure Java Yes Yes Yes No No
Memory Mode Yes Yes Yes No No
Encrypted Database Yes Yes Yes No No
ODBC Driver Yes No No Yes Yes
Fulltext Search Yes No No Yes Yes
Multi Version Concurrency Yes No Yes Yes Yes
Footprint (jar/dll size) ~1 MB ~2 MB ~1 MB ~4 MB ~6 MB

作用

可以和 DBUnit 这种数据测试框架结合使用。

Hello World

  • 引入 jar
<dependencies>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.196</version>
    </dependency>
</dependencies>
  • 入门测试
import org.h2.tools.Server;

import java.sql.*;

/**
 * H2 入门测试案例
 * @author bbhou
 */
public class HelloH2 {

    private Server server;

    private static final String URL = "jdbc:h2:mem:h2db";
    private static final String PORT = "8082";
    private static final String USERNAME = "sa";
    private static final String PASSWORD = "123456";

    /**
     * 启动服务
     */
    public void startServer() {
        try {
            System.out.println("正在启动h2...");
            server = Server.createTcpServer(
                    new String[] { "-tcpPort", PORT}).start();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止服务
     */
    public void stopServer() {
        if (server != null) {
            System.out.println("正在关闭h2...");
            server.stop();
            System.out.println("关闭成功.");
        }
    }

    /**
     * 简单测试
     */
    public void testH2() {
        // 加载驱动
        try {
            Class.forName("org.h2.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try(Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            Statement statement = connection.createStatement()){

            // 插入数据
            statement.execute("CREATE MEMORY Table test(NAME VARCHAR)");
            statement.execute("INSERT INTO test VALUES('Hello H2DB!')");

            // 查询数据
            try(ResultSet result = statement.executeQuery("SELECT NAME FROM test")) {
                while (result.next()) {
                    System.out.println(result.getString("name"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HelloH2 h2 = new HelloH2();

        // 开始服务
        h2.startServer();
        h2.testH2();
        // 关闭服务
        h2.stopServer();
    }
}
  • 测试结果
正在启动h2...
Hello H2DB!
正在关闭h2...
关闭成功.