本例开发工具为 NetBeans,使用b2前提安装jdk.
第一步:在官网下载驱动包 :http://www.h2database.com ,本例版本为: h2-1.4.192.jar
第二步:安装开发工具及jdk
(1) 开发工具为:netbeans 8.0.2
(2) jdk为 1.8.0.25
第三步:建立工程及代码如下
(1) 工程图
(2) 代码如下
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package h2db.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.h2.tools.Server; /** * * @author NorthEastTycoon */ public class H2Demo { private Server server; private String port = "8082"; private static String sourceURL1 = "jdbc:h2:mem:h2db"; private static String sourceURL2 = "jdbc:h2:tcp://192.168.19.1:8082/mem:h2db"; private String user = "sa"; private String password = ""; public void startServer() { try { System.out.println("正在启动h2..."); server = Server.createTcpServer( new String[] { "-tcpPort", port }).start(); } catch (SQLException e) { System.out.println("启动h2出错:" + e.toString()); e.printStackTrace(); throw new RuntimeException(e); } } public void stopServer() { if (server != null) { System.out.println("正在关闭h2..."); server.stop(); System.out.println("关闭成功."); } } public void testH2() { try { // 加载驱动 Class.forName("org.h2.Driver"); // 创建连接 Connection conn = DriverManager.getConnection(sourceURL1,user, password); Statement stat = conn.createStatement(); // 插入数据 stat.execute("CREATE MEMORY Table table_one(NAME VARCHAR)"); stat.execute("INSERT INTO table_one VALUES('this is my first program!')"); // 查询数据 ResultSet result = stat.executeQuery("select name from table_one "); int i = 1; while (result.next()) { System.out.println(i++ + ":" + result.getString("name")); } result.close(); stat.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { H2Demo h2 = new H2Demo(); // 开始服务 h2.startServer(); h2.testH2(); // 关闭服务 h2.stopServer(); } }
(3) 输出结果