H2數(shù)據(jù)庫使用

H2 Database (http://www.h2database.com/html/main.html) 是一個(gè)開源的嵌入式數(shù)據(jù)庫引擎登夫,采用java語言編寫璃诀,支持SQL月培,同時(shí)H2提供了一個(gè)十分方便的web控制臺(tái)用于操作和管理數(shù)據(jù)庫內(nèi)容。

H2 官網(wǎng)介紹如下:

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

Connection Modes

The following connection modes are supported:

  • Embedded mode (local connections using JDBC)
  • Server mode (remote connections using JDBC or ODBC over TCP/IP)
  • Mixed mode (local and remote connections at the same time)

Embedded Mode

This database can be used in embedded mode, or in server mode. To use it in embedded mode, you need to:

  • Add the h2*.jar to the classpath (H2 does not have any dependencies)
  • Use the JDBC driver class: org.h2.Driver
  • The database URL jdbc:h2:~/test opens the database test in your user home directory
  • A new database is automatically created

Server Mode

H2 currently supports three server: a web server (for the H2 Console), a TCP server (for client/server connections) and an PG server (for PostgreSQL clients). Please note that only the web server supports browser connections. The servers can be started in different ways, one is using the Server tool. Starting the server doesn't open a database - databases are opened as soon as a client connects.

Starting the Server Tool from Command Line

To start the Server tool from the command line with the default settings, run:

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

Connecting to the TCP Server

o remotely connect to a database using the TCP server, use the following driver and database URL:

  • JDBC driver class: org.h2.Driver
  • Database URL: jdbc:h2:tcp://localhost/~/test

Database URL

Topic URL Format and Examples
Embedded (local) connection jdbc:h2:[file:][<path>]<databaseName>
jdbc:h2:~/test
jdbc:h2:file:/data/sample
jdbc:h2:file:C:/data/sample (Windows only)
In-memory (private) jdbc:h2:mem:
In-memory (named) jdbc:h2:mem:<databaseName>
jdbc:h2:mem:test_mem
Server mode (remote connections) using TCP/IP jdbc:h2:tcp://<server>[:<port>]/[<path>]<databaseName>
jdbc:h2:tcp://localhost//test<br>jdbc:h2:tcp://dbserv:8084//sample
jdbc:h2:tcp://localhost/mem:test
Using encrypted files jdbc:h2:<url>;CIPHER=AES
jdbc:h2:ssl://localhost//test;CIPHER=AES<br>jdbc:h2:file:/secure;CIPHER=AES

完整內(nèi)容:Database URL Overview

實(shí)戰(zhàn)

maven依賴:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.193</version>
</dependency>

創(chuàng)建本地文件數(shù)據(jù)庫

代碼如下:

       Connection conn = null;
        try{
            Class.forName("org.h2.Driver");
            conn = DriverManager. getConnection("jdbc:h2:~/test", "sa", "sa");
            
            //do your business
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

創(chuàng)建本地內(nèi)存數(shù)據(jù)庫

        Connection conn = null;
        try{
            Class.forName("org.h2.Driver");
            conn = DriverManager. getConnection("jdbc:h2:mem:test_mem", "sa", "sa");

            // do your business

        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

創(chuàng)建表

SQL:

CREATE TABLE t_user (
    id BIGINT NOT NULL, 
    name VARCHAR(20) NOT NULL,
    password VARCHAR(32) NOT NULL, 
    age SMALLINT, 
    birthday TIMESTAMP,
    PRIMARY KEY (id)
);

代碼如下:

package com.bytebeats.codelab.h2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2017-03-05 14:43
 */
public class CreateTable {

    public static void main(String[] args) {

        Connection conn = null;
        Statement stmt = null;
        try{
            Class.forName("org.h2.Driver");
            conn = DriverManager. getConnection("jdbc:h2:~/test", "sa", "sa");

            stmt = conn.createStatement();

            int result = stmt.executeUpdate("CREATE TABLE t_user (" +
                    "id BIGINT NOT NULL, " +
                    "name VARCHAR(20) NOT NULL," +
                    "password VARCHAR(32) NOT NULL, " +
                    "age SMALLINT, " +
                    "birthday TIMESTAMP," +
                    "PRIMARY KEY (id)" +
                    ");");

            System.out.println("result:"+result);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

插入記錄

INSERT INTO t_user VALUES (1,'ricky', '12345', 28, '1989-09-15 15:00:00');

代碼如下:

package com.bytebeats.codelab.h2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2017-03-05 14:57
 */
public class InsertQuery {

    public static void main(String[] args) {

        Connection conn = null;
        Statement stmt = null;
        try{
            Class.forName("org.h2.Driver");
            conn = DriverManager. getConnection("jdbc:h2:~/test", "sa", "sa");

            stmt = conn.createStatement();
            int update = stmt.executeUpdate("INSERT INTO t_user VALUES (1,'ricky', '12345', 28, '1989-09-15 15:00:00');");
            System.out.println(update);

        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

查詢記錄

SQL:

SELECT id, name, password, age, birthday FROM t_user where id=1

代碼如下:

package com.bytebeats.codelab.h2;

import java.sql.*;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2017-03-05 14:57
 */
public class SelectQuery {

    public static void main(String[] args) {

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet result = null;
        try{
            Class.forName("org.h2.Driver");
            conn = DriverManager. getConnection("jdbc:h2:~/test", "sa", "sa");

            stmt = conn.prepareStatement("SELECT id, name, password, age, birthday FROM t_user WHERE id=?");
            stmt.setLong(1, 1);

            result = stmt.executeQuery();
            while(result.next()){
                System.out.println(result.getInt("id")+" | "+
                        result.getString("name")+" | "+
                        result.getString("password")+" | "+
                        result.getShort("age")+" | "+
                        result.getTimestamp("birthday"));
            }

        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                result.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

參考資料

更多用法參考:H2 Database features

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末夫椭,一起剝皮案震驚了整個(gè)濱河市掸掸,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌益楼,老刑警劉巖猾漫,帶你破解...
    沈念sama閱讀 211,290評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件点晴,死亡現(xiàn)場(chǎng)離奇詭異感凤,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)粒督,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門陪竿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人屠橄,你說我怎么就攤上這事族跛。” “怎么了锐墙?”我有些...
    開封第一講書人閱讀 156,872評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵礁哄,是天一觀的道長。 經(jīng)常有香客問我溪北,道長桐绒,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,415評(píng)論 1 283
  • 正文 為了忘掉前任之拨,我火速辦了婚禮茉继,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蚀乔。我一直安慰自己烁竭,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評(píng)論 6 385
  • 文/花漫 我一把揭開白布吉挣。 她就那樣靜靜地躺著派撕,像睡著了一般婉弹。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上终吼,一...
    開封第一講書人閱讀 49,784評(píng)論 1 290
  • 那天马胧,我揣著相機(jī)與錄音,去河邊找鬼衔峰。 笑死佩脊,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的垫卤。 我是一名探鬼主播威彰,決...
    沈念sama閱讀 38,927評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼穴肘!你這毒婦竟也來了歇盼?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,691評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎邻寿,沒想到半個(gè)月后竟纳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,137評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡邢笙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評(píng)論 2 326
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了侍匙。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片氮惯。...
    茶點(diǎn)故事閱讀 38,622評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖想暗,靈堂內(nèi)的尸體忽然破棺而出妇汗,到底是詐尸還是另有隱情,我是刑警寧澤说莫,帶...
    沈念sama閱讀 34,289評(píng)論 4 329
  • 正文 年R本政府宣布杨箭,位于F島的核電站,受9級(jí)特大地震影響储狭,放射性物質(zhì)發(fā)生泄漏互婿。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評(píng)論 3 312
  • 文/蒙蒙 一晶密、第九天 我趴在偏房一處隱蔽的房頂上張望擒悬。 院中可真熱鬧,春花似錦稻艰、人聲如沸懂牧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽僧凤。三九已至畜侦,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間躯保,已是汗流浹背旋膳。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留途事,地道東北人验懊。 一個(gè)月前我還...
    沈念sama閱讀 46,316評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像尸变,于是被迫代替她去往敵國和親义图。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容