连接:http://www.h2database.com/html/main.html
快速开始
- 引入 h2*.jar
- 加载驱动 org.h2.Driver
- 设置URL jdbc:h2:~/test
特征
- 非常快,开源,JDBC API
- 嵌入式和服务器模式;基于磁盘或内存中的数据库
- 事务支持,多版本并发
- 基于浏览器的控制台应用程序
- 加密数据库
- 全文搜索
- 占用空间小的纯 Java:大约 2.5 MB 的 jar 文件大小
- ODBC 驱动程序
H2数据库有三种运行方式实现
嵌入式(embedded):
可以同应用程序打包在一起发布,这样可以非常方便地存储少量结构化数据
服务模式:
1.TCP/IP server:支持客户端/服务器端的连接方式
2.web server:此种运行方式支持使用浏览器访问H2 Console
3.PG server:支持PostgreSQL客户端
内存方式:可以作为缓存,作为NoSQL的一个补充。
当某些场景下数据模型必须为关系型,可以拿它当Memcached使,作为后端MySQL/Oracle的一个缓冲层,缓存一些不经常变化但需要频繁访问的数据,比如字典表、权限表。
注意:H2查询 大小写不敏感,
数据库文件存储在哪里?
当使用像 jdbc:h2:~/test 这样的数据库 URL 时,数据库存储在用户目录中.对于 Windows,这通常是 C:Documents and Settings 或 C:Users.如果未设置基本目录(如jdbc:h2:./test),则数据库文件存储在应用程序启动的目录(当前工作目录)中.从开始菜单使用 H2 Console 应用程序时,这是 /bin.可以在数据库 URL 中设置基本目录.可以使用固定或相对路径.当使用 URL jdbc:h2:file:./data/sample 时,数据库存储在目录 data 中(相对于当前工作目录).如果该目录尚不存在
private static String jdbcURL = "jdbc:h2:~/desgin";private static String jdbcUsername = "desgin";private static String jdbcPassword = "desgin";public static Connection getConnection() {Connection connection = null;try {connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return connection;}
private static final String createTableSQL = "create table users\n" +"(\n" +"\tid bigint auto_increment,\n" +"\tname varchar(64),\n" +"\tage int,\n" +"\tconstraint USERS_PK\n" +"\t\tprimary key (id)\n" +");\n";public void createTable() throws SQLException {// Step 1: Establishing a Connectiontry (Connection connection = H2JDBCUtils.getConnection();// Step 2:Create a statement using connection objectStatement statement = connection.createStatement();) {// Step 3: Execute the query or update querystatement.executeUpdate(createTableSQL);} catch (SQLException e) {// print SQL exception informationH2JDBCUtils.printSQLException(e);}}
private static final String QUERY = "select id,name,age from users where id =?";public static void main(String[] args) {// using try-with-resources to avoid closing resources (boiler plate code)// Step 1: Establishing a Connectiontry (Connection connection = H2JDBCUtils.getConnection();// Step 2:Create a statement using connection objectPreparedStatement preparedStatement = connection.prepareStatement(QUERY);) {preparedStatement.setInt(1, 1);System.out.println(preparedStatement);// Step 3: Execute the query or update queryResultSet rs = preparedStatement.executeQuery();// Step 4: Process the ResultSet object.while (rs.next()) {int id = rs.getInt("id");String name = rs.getString("name");int email = rs.getInt("age");System.out.println(id + "," + name + "," + email );}} catch (SQLException e) {H2JDBCUtils.printSQLException(e);}// Step 4: try-with-resource statement will auto close the connection.}
