HSQL 数据库介绍(2)--使用

一给  金牌会员 | 2024-7-14 21:29:13 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 857|帖子 857|积分 2571

本文主要介绍 HSQLDB 的基本使用,文中所使用到的软件版本:Java 11.0.22、HSQLDB 2.7.2。
1、进程内模式

直接使用 JDBC 连接数据库即可,如果数据库不存在会自动创建。
1.1、file 数据库
  1. @Test
  2. public void inProcessFile() throws SQLException {
  3.     String dbName = "test";
  4.     //用户名密码为第一次连接设置的密码
  5.     Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:file:d:/temp/" + dbName, "admin", "123456");
  6.     log.info("con={}", con);
  7.     business(con);
  8.     con.close();
  9. }
  10. private void business(Connection con) throws SQLException {
  11.     String tableName = "a_student";
  12.     Statement st = con.createStatement();
  13.     String sql = "select 1 from INFORMATION_SCHEMA.TABLES where upper(table_schema)=? and upper(table_name)=?";
  14.     PreparedStatement pst = con.prepareStatement(sql);
  15.     pst.setString(1, "PUBLIC");
  16.     pst.setString(2, tableName.toUpperCase());
  17.     ResultSet rs = pst.executeQuery();
  18.     if (!rs.next()) {//表不存在则创建并初始化数据,这里根据业务需要进行操作
  19.         st.executeUpdate("create table " + tableName + "(id int, name varchar(32))");
  20.         st.executeUpdate("insert into " + tableName + "(id,name) values (1,'李白')");
  21.         st.executeUpdate("insert into " + tableName + "(id,name) values (2,'杜甫')");
  22.     }
  23.     rs = st.executeQuery("select * from " + tableName);
  24.     while (rs.next()) {
  25.         log.info("id={},name={}", rs.getInt("id"), rs.getString("name"));
  26.     }
  27. }
复制代码
1.2、mem 数据库
  1. @Test
  2. public void inProcessMem() throws SQLException {
  3.     String dbName = "test";
  4.     //用户名密码为第一次连接设置的密码
  5.     Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:mem:" + dbName, "admin", "123456");
  6.     log.info("con={}", con);
  7.     business(con);
  8.     con.close();
  9. }
复制代码
1.3、res 数据库
  1. @Test
  2. public void inProcessRes() throws SQLException {
  3.     String dbName = "test";
  4.     //用户名密码为第一次连接设置的密码,数据库文件位于某个依赖 jar 文件的 db 目录中
  5.     Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:res:db/" + dbName, "admin", "123456");
  6.     log.info("con={}", con);
  7.     business(con);
  8.     con.close();
  9. }
复制代码
2、服务器模式

2.1、HyperSQL HSQL Server

可以通过如下命令启动 HyperSQL HSQL Server,假设当前位于 HSQLDB 安装包的 data 目录中:
  1. java -cp ../lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:d:/temp/mydb --dbname.0 test #启动file数据库,数据库文件保存在d:/temp目录下,数据名称为 test
  2. java -cp ../lib/hsqldb.jar org.hsqldb.server.Server --database.0 mem:mydb --dbname.0 test #启动mem数据库,数据名称为 test
复制代码
可以添加其他参数来调解数据库的默认行为,查看所有参数:
  1. java  -cp ../lib/hsqldb.jar org.hsqldb.server.Server --help
复制代码
相关参数如下:
  1. Usage: java org.hsqldb.server.WebServer [options]
  2. +-----------------+------------ +------------+------------------------------+
  3. |     OPTION      |    TYPE     |  DEFAULT   |         DESCRIPTION          |
  4. +-----------------+-------------+------------+------------------------------|
  5. | --help          | -           | -          | displays this message        |
  6. | --address       | name|number | any        | server inet address          |
  7. | --port          | number      | 80/443     | port at which server listens |
  8. | --database.i    | [type]spec  | 0=test     | name of database i           |
  9. | --dbname.i      | alias       | -          | url alias for database i     |
  10. | --root          | path        | ./         | path to web root             |
  11. | --default_page  | file        | index.html | default web page             |
  12. | --silent        | true|false  | true       | false => display all queries |
  13. | --trace         | true|false  | false      | display JDBC trace messages  |
  14. | --tls           | true|false  |            | HTTPS (secure) sockets       |
  15. | --no_system_exit| true|false  | false      | do not issue System.exit()   |
  16. | --remote_open   | true|false  | false      | can open databases remotely  |
  17. | --props         | filepath    |            | file path of properties file |
  18. +-----------------+-------------+------------+------------------------------+
  19. The web server looks for a 'webserver.properties' file in the current directory
  20. and loads properties from it if it exists.
  21. Command line options override those loaded from the 'webserver.properties' file.
复制代码
启动后使用 JDBC 访问数据库:
  1. @Test
  2. public void hsqlServer() throws SQLException {
  3.     String dbName = "test";
  4.     Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:hsql://localhost:9001/" + dbName, "SA", "");
  5.     log.info("con={}", con);
  6.     business(con);
  7.     con.close();
  8. }
复制代码
2.2、HyperSQL HTTP Server

可以通过如下命令启动 HyperSQL HTTP Server,假设当前位于 HSQLDB 安装包的 data 目录中:
  1. java -cp ../lib/hsqldb.jar org.hsqldb.server.WebServer --database.0 file:d:/temp/mydb --dbname.0 test #启动file数据库,数据库文件保存在d:/temp目录下,数据名称为 test
  2. java -cp ../lib/hsqldb.jar org.hsqldb.server.WebServer --database.0 mem:mydb --dbname.0 test #启动mem数据库,数据名称为 test
复制代码
可以添加其他参数来调解数据库的默认行为,查看所有参数:
  1. java  -cp ../lib/hsqldb.jar org.hsqldb.server.WebServer --help
复制代码
相关参数如下:
  1. Usage: java org.hsqldb.server.WebServer [options]
  2. +-----------------+------------ +------------+------------------------------+
  3. |     OPTION      |    TYPE     |  DEFAULT   |         DESCRIPTION          |
  4. +-----------------+-------------+------------+------------------------------|
  5. | --help          | -           | -          | displays this message        |
  6. | --address       | name|number | any        | server inet address          |
  7. | --port          | number      | 80/443     | port at which server listens |
  8. | --database.i    | [type]spec  | 0=test     | name of database i           |
  9. | --dbname.i      | alias       | -          | url alias for database i     |
  10. | --root          | path        | ./         | path to web root             |
  11. | --default_page  | file        | index.html | default web page             |
  12. | --silent        | true|false  | true       | false => display all queries |
  13. | --trace         | true|false  | false      | display JDBC trace messages  |
  14. | --tls           | true|false  |            | HTTPS (secure) sockets       |
  15. | --no_system_exit| true|false  | false      | do not issue System.exit()   |
  16. | --remote_open   | true|false  | false      | can open databases remotely  |
  17. | --props         | filepath    |            | file path of properties file |
  18. +-----------------+-------------+------------+------------------------------+
  19. The web server looks for a 'webserver.properties' file in the current directory
  20. and loads properties from it if it exists.
  21. Command line options override those loaded from the 'webserver.properties' file.
复制代码
启动后使用 JDBC 访问数据库:
  1. @Test
  2. public void httpServer() throws SQLException {
  3.     String dbName = "test";
  4.     Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:http://localhost:80/" + dbName, "SA", "");
  5.     log.info("con={}", con);
  6.     business(con);
  7.     con.close();
  8. }
复制代码
2.3、HyperSQL HTTP Servlet

这种方式使用较少,这里就不详细介绍,可参考源文件 src/org/hsqldb/server/Servlet.java 查看详细信息。
3、混合模式

应用通过代码的方式启动数据库服务,应用内访问数据库可以使用进程模式,其他应用通过服务器模式访问。下面衍生通过代码分别启动 HyperSQL HSQL Server 和 HyperSQL HTTP Server,然后模仿其他应用访问数据库。
3.1、HyperSQL HSQL Server
  1. @Test
  2. public void hsqlServer2() throws Exception {
  3.     HsqlProperties p = new HsqlProperties();
  4.     //三种数据库类型,根据需要选择合适的一个
  5.     p.setProperty("server.database.0","file:d:/temp/mydb");
  6.     //p.setProperty("server.database.0","mem:mydb");
  7.     //p.setProperty("server.database.0","res:db/test");//数据库文件test.xx位于某个依赖jar文件的 db 目录中
  8.     p.setProperty("server.dbname.0","test");
  9.     Server server = new Server();
  10.     server.setProperties(p);
  11.     server.start();
  12.     CountDownLatch countDownLatch = new CountDownLatch(1);
  13.     new Thread(() -> {
  14.         try {
  15.             //模拟其他应用访问
  16.             hsqlServer();
  17.         } catch (Exception e) {
  18.             e.printStackTrace();
  19.         }
  20.         countDownLatch.countDown();
  21.     }).start();
  22.     countDownLatch.await();
  23.     server.shutdownCatalogs(1);
  24.     server.stop();
  25. }
复制代码
Server 的属性设置参数可参考 2.1 中启动数据库时的命令行参数。
3.2、HyperSQL HTTP Server
  1. @Test
  2. public void httpServer2() throws Exception {
  3.     HsqlProperties p = new HsqlProperties();
  4.     //三种数据库类型,根据需要选择合适的一个
  5.     //p.setProperty("server.database.0","file:d:/temp/mydb");
  6.     //p.setProperty("server.database.0","mem:mydb");
  7.     p.setProperty("server.database.0","res:db/test");//数据库文件test.xx位于某个依赖jar文件的 db 目录中
  8.     p.setProperty("server.dbname.0","test");
  9.     WebServer webServer = new WebServer();
  10.     webServer.setProperties(p);
  11.     webServer.start();
  12.    
  13.     CountDownLatch countDownLatch = new CountDownLatch(1);
  14.     new Thread(() -> {
  15.         try {
  16.             //模拟其他应用访问
  17.             httpServer();
  18.         } catch (Exception e) {
  19.             e.printStackTrace();
  20.         }
  21.         countDownLatch.countDown();
  22.     }).start();
  23.     countDownLatch.await();
  24.     webServer.stop();
  25. }
复制代码
WebServer 的属性设置参数可参考 2.2 中启动数据库时的命令行参数。
 
完备代码:
  1. package com.abc.demo.db;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.hsqldb.Server;
  4. import org.hsqldb.persist.HsqlProperties;
  5. import org.hsqldb.server.WebServer;
  6. import org.junit.Test;
  7. import java.sql.*;
  8. import java.util.concurrent.CountDownLatch;
  9. @Slf4j
  10. public class HSQLCase {
  11.     @Test
  12.     public void inProcessFile() throws SQLException {
  13.         String dbName = "test";
  14.         //用户名密码为第一次连接设置的密码
  15.         Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:file:d:/temp/" + dbName, "admin", "123456");
  16.         log.info("con={}", con);
  17.         business(con);
  18.         con.close();
  19.     }
  20.     @Test
  21.     public void inProcessMem() throws SQLException {
  22.         String dbName = "test";
  23.         //用户名密码为第一次连接设置的密码
  24.         Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:mem:" + dbName, "admin", "123456");
  25.         log.info("con={}", con);
  26.         business(con);
  27.         con.close();
  28.     }
  29.     @Test
  30.     public void inProcessRes() throws SQLException {
  31.         String dbName = "test";
  32.         //用户名密码为第一次连接设置的密码,数据库文件位于某个依赖 jar 文件的 db 目录中
  33.         Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:res:db/" + dbName, "admin", "123456");
  34.         log.info("con={}", con);
  35.         business(con);
  36.         con.close();
  37.     }
  38.     @Test
  39.     public void hsqlServer() throws SQLException {
  40.         String dbName = "test";
  41.         Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:hsql://localhost:9001/" + dbName, "SA", "");
  42.         log.info("con={}", con);
  43.         business(con);
  44.         con.close();
  45.     }
  46.     @Test
  47.     public void httpServer() throws SQLException {
  48.         String dbName = "test";
  49.         Connection con = JdbcUtil.getConnection("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:http://localhost:80/" + dbName, "SA", "");
  50.         log.info("con={}", con);
  51.         business(con);
  52.         con.close();
  53.     }
  54.     @Test
  55.     public void hsqlServer2() throws Exception {
  56.         HsqlProperties p = new HsqlProperties();
  57.         //三种数据库类型,根据需要选择合适的一个
  58.         p.setProperty("server.database.0","file:d:/temp/mydb");
  59.         //p.setProperty("server.database.0","mem:mydb");
  60.         //p.setProperty("server.database.0","res:db/test");//数据库文件test.xx位于某个依赖jar文件的 db 目录中
  61.         p.setProperty("server.dbname.0","test");
  62.         Server server = new Server();
  63.         server.setProperties(p);
  64.         server.start();
  65.         CountDownLatch countDownLatch = new CountDownLatch(1);
  66.         new Thread(() -> {
  67.             try {
  68.                 //模拟其他应用访问
  69.                 hsqlServer();
  70.             } catch (Exception e) {
  71.                 e.printStackTrace();
  72.             }
  73.             countDownLatch.countDown();
  74.         }).start();
  75.         countDownLatch.await();
  76.         server.shutdownCatalogs(1);
  77.         server.stop();
  78.     }
  79.     @Test
  80.     public void httpServer2() throws Exception {
  81.         HsqlProperties p = new HsqlProperties();
  82.         //三种数据库类型,根据需要选择合适的一个
  83.         //p.setProperty("server.database.0","file:d:/temp/mydb");
  84.         //p.setProperty("server.database.0","mem:mydb");
  85.         p.setProperty("server.database.0","res:db/test");//数据库文件test.xx位于某个依赖jar文件的 db 目录中
  86.         p.setProperty("server.dbname.0","test");
  87.         WebServer webServer = new WebServer();
  88.         webServer.setProperties(p);
  89.         webServer.start();
  90.         CountDownLatch countDownLatch = new CountDownLatch(1);
  91.         new Thread(() -> {
  92.             try {
  93.                 //模拟其他应用访问
  94.                 httpServer();
  95.             } catch (Exception e) {
  96.                 e.printStackTrace();
  97.             }
  98.             countDownLatch.countDown();
  99.         }).start();
  100.         countDownLatch.await();
  101.         webServer.stop();
  102.     }
  103.     private void business(Connection con) throws SQLException {
  104.         String tableName = "a_student";
  105.         Statement st = con.createStatement();
  106.         String sql = "select 1 from INFORMATION_SCHEMA.TABLES where upper(table_schema)=? and upper(table_name)=?";
  107.         PreparedStatement pst = con.prepareStatement(sql);
  108.         pst.setString(1, "PUBLIC");
  109.         pst.setString(2, tableName.toUpperCase());
  110.         ResultSet rs = pst.executeQuery();
  111.         if (!rs.next()) {//表不存在则创建并初始化数据,这里根据业务需要进行操作
  112.             st.executeUpdate("create table " + tableName + "(id int, name varchar(32))");
  113.             st.executeUpdate("insert into " + tableName + "(id,name) values (1,'李白')");
  114.             st.executeUpdate("insert into " + tableName + "(id,name) values (2,'杜甫')");
  115.         }
  116.         rs = st.executeQuery("select * from " + tableName);
  117.         while (rs.next()) {
  118.             log.info("id={},name={}", rs.getInt("id"), rs.getString("name"));
  119.         }
  120.     }
  121. }
复制代码
HSQLCase.java
  1. package com.abc.demo.db;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.sql.*;
  4. @Slf4j
  5. public class JdbcUtil {
  6.     private JdbcUtil() {}
  7.     public static Connection getConnection(String driver, String url, String username, String password) {
  8.         Connection con = null;
  9.         try {
  10.             Class.forName(driver);
  11.             con = DriverManager.getConnection(url, username, password);
  12.         } catch (ClassNotFoundException | SQLException e) {
  13.             log.warn("url={},username={},password={}", url, username, password);
  14.             e.printStackTrace();
  15.         }
  16.         return con;
  17.     }
  18. }
复制代码
JdbcUtil.java 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

一给

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表