Novice web development simple summary (7)-database HSQLDB

table of Contents

I. Introduction

二 HSQLDB

1. What is HSQLDB

2. Installation of HSQLDB

Three HSQLDB database engine

1. Server mode

Server mode

 WebServer mode

Servlet mode

2. Process mode (In-Process)

3. Memory (Memory-Only) mode

4. Summary

Four HSQLDB database driver

Five HSQLDB database user operation interface

1. Configure HSQLDB database tools

2. Other tools

Six summary


I. Introduction

The last novice web development brief summary (6)-Spring's IoC container mainly summarizes what is Spring. In the process of web application development, it is inseparable from reading and writing databases. Databases are divided into relational databases and non-relational databases.

A relational database has a data structure composed of two-dimensional tables and direct connections (tuples, attributes, fields, keywords, etc.). This two-dimensional table is commonly referred to as the table name; tuples are each row in the table, usually called records; attributes are each column in the table, usually called fields; domains are a range of values ​​for attributes; The key is the primary key, usually composed of one or more columns.

Common relational databases are: Oracle, MySQL, PosgreSQL, SQLite, SQL Server, sqlite, etc.

Java programs provide a JDBC interface to access relational databases usually requires the following steps:

  public static void main(String[] args) {
        String url = "";
        String user = "";
        String password = "";
        /**
         *  表示一个数据库的连接
         */
        Connection connection = null;
        /**
         * 执行数据库SQL语句,并返回相应结果的对象,其中Statement有两个子接口:
         * PreparedStatement:预编译对象,用于解决sql的注入问题;
         * CallableStatement:支持带参数的SQL操作,支持调用存储过程,是PreparedStatement的子接口
         */
        Statement statement;
        /**
         * 用来存储执行SQL语句返回的结果
         */
        ResultSet set;
      
        //1.初始化JDBC驱动
        try {
          
            Class.forName("org.hsqldb.jdbcDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("ERROR:failed to load jdbc driver");
            return;
        }
        //2.开始读取相关的数据库文件
        try {
            //(1).使用DriverManager来注册驱动,创建数据库的连接对象Connection
            connection = DriverManager.getConnection(url, user, password);
            //(2).通过Connection获得执行数据库语句的对象Statement
            statement = connection.createStatement();
            //(3).创建一个查询语句,返回查询的结果
            set = statement.executeQuery("select * from user");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

 

Non-relational databases are stored in key-value pairs, and the structure is not fixed. Each tuple can have different fields, and each tuple can add its own key-value pairs as needed.

Common non-relational databases include Memcached with a key-value structure, MongoDB with JSON storage, and Splunk with NoSQL for searching data content.

And this time, I will simply learn the HSQLDB database in the relational database.

二 HSQLDB

1. What is HSQLDB

HSQLDB (HyperSQL Database), an open source java database with standard SQL syntax and Java interface. Small in size, it can be used without complicated database configuration, suitable for small data.

The jar package provided by the official website includes the database engine (HyperSQL RDBMS Engine (HSQLDB)) , database driver (HyperSQL JDBC Driver) and other user interface operations (Database Manager, Sql Tool, etc.) .

An HSQLDB is called a catalog, which usually contains 2-6 files, located in the same directory, but with different extensions:

  • .properties: the basic configuration of the database
  • .script: definition of tables and other database objects
  • .log: recent changes to the database
  • .data: buffer table data
  • .backup: The backup compressed file of the data file, which saves the last final state data.

If there is no cached table, .data and .backup will not exist.

2. Installation of HSQLDB

As long as it supports JDK. Download the corresponding .zip on the official website and unzip it to any directory.

  • (1) Go directly to the official website  http://hsqldb.org and click on the link shown in the figure below:

  • (3) After downloading and decompressing, as shown in the figure, the core jar package hsqldb.jar is in the lib directory.

 Usually, the created database file is stored in the data directory. The lib directory stores the core hsqldb.jar package, and the HSQLDB database can be started and managed through the jar package.

Three HSQLDB database engine

The so-called database engine is the core part used to store, process and protect data. Use the database engine to control access rights and quickly process transactions. Access the database file through the data engine. The HSQLDB database engine is divided into three modes: Server mode, In-Process mode, and Memory-Only mode.

1. Server mode

A separate JVM will be started to provide database services, just like Oracle, MySql and other databases. After the database is started, it will exist as a server, and web applications can connect to the database service through the JDBC driver. Up to 10 database connections can be specified.

Server mode is divided into Server mode, WebServer mode, and Servlet mode.

Server mode

  • (1) Communication protocol

Adopt HSQLDB's proprietary communication protocol.

  • (2) Create or connect to the database

Create or connect to a database through hsqldb.jar (create a new database if it does not exist, or just connect to an existing database) as follows:

Execute the following commands in the data directory:

MacBook-Pro:data j1$ java -cp ../lib/hsqldb.jar  org.hsqldb.Server -database.0 ./ec-goods/book -dbname.0 xbook

-database.n represents the address and name of the database file, supports relative paths, followed by "database address/database name";

-dbname.n represents the alias of the database file, which is used to access the database in the code.

The .n after -databse and -dbname indicates that multiple databases can be created or connected, and the maximum number supported is 10. Example to create or connect to multiple databases at once:

MacBook-Pro:data j1$ java -cp ../lib/hsqldb.jar  org.hsqldb.Server -database.0 ./ec-goods/book -dbname.0 xbook -database.1 ./ec-goods1/book1 -dbname.1 xbook1
[Server@87aac27]: Startup sequence initiated from main() method
[Server@87aac27]: Could not load properties from file
[Server@87aac27]: Using cli/default properties only
[Server@87aac27]: Initiating startup sequence...
[Server@87aac27]: Server socket opened successfully in 9 ms.
[Server@87aac27]: Database [index=0, id=0, db=file:./ec-goods1/book1, alias=xbook1] opened successfully in 255 ms.
[Server@87aac27]: Database [index=1, id=1, db=file:./ec-goods/book, alias=xbook] opened successfully in 27 ms.
[Server@87aac27]: Startup sequence completed in 291 ms.
[Server@87aac27]: 2021-02-24 06:25:55.081 HSQLDB server 2.5.1 is online on port 9001
[Server@87aac27]: To close normally, connect and execute SHUTDOWN SQL
[Server@87aac27]: From command line, use [Ctrl]+[C] to abort abruptly

After entering the data directory, these two tables were found and added, and the files corresponding to each table are the files we mentioned in the second part, where .lok means the database is open.

  • (3) Code to obtain Connection instance

The jdbc-url of this mode is: jdbc:hsqldb:hsql://localhost/database alias , the code to obtain the Connection instance is as follows:

 Connection connection = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/xbook", user, password);

 WebServer mode

  • (1) Communication protocol

HTTP protocol. Mainly used for firewall, the default port is 9001

  • (2) Create or connect to the database

The command is still executed in the data directory through hsqldb.jar, but org.hsqldb.Server is replaced by org.hsqldb.server.WebServer, as shown in the figure:

MacBook-Pro:data j1$ java -cp ../lib/hsqldb.jar   org.hsqldb.server.WebServer -database.0 ./ec-goods/book -dbname.0 xbook
  • (3) Code to obtain Connection instance

The jdbc-url of this mode is: jdbc:hsqldb:http://localhost/database alias , the code example is as follows:

 Connection connection = DriverManager.getConnection("jdbc:hsqldb:http://localhost/xbook", user, password);

Servlet mode

Same as the WebServer mode, it also uses the HTTP protocol as the communication protocol. Mainly to provide database access for Tomcat and other application servers using Servlet containers. And the created database cannot be separated from the Servlet engine server, and the Servlet class in the Hsqldb.jar package must be placed in the corresponding position of the application server.

Usually the database engine of the application server will not adopt this mode.

The jdbc-url of this mode is: also jdbc:hsqldb:http://localhost/ database alias .

2. Process mode (In-Process)

  • (1) Communication method

Also known as Standalone mode. As part of the application, the data runs in the same JVM. There is no need to use data conversion and network transmission, and directly operate in file mode. The access speed is fast. All data will be written to the file. After the database is closed, the data is still retained.

But this mode can only be used in the current application. When the application is started, other applications cannot access the contents of the database.

  • (2) Create or connect to the database

Compared with the server mode, this method will create a database when the Connection is obtained through the DriverManager.

   Connection connection = DriverManager.getConnection("jdbc:hsqldb:file:user", user, password);

 The jdbc-url here is: dbc:hsqldb:file:path/database table name . Paths can support both absolute paths and relative paths: that is to say:

jdbc:hsqldb:file:user: create a user table in the current directory of the project

"jdbc:hsqldb:file:db/user": create a user table in the db directory of the current directory of the project

"jdbc:hsqldb:file:/Users/j1/Documents/java/db/user": create a user table in the local directory

"Jdbc:hsqldb:res:org.my.path.resdb": In this case, databases in some Java resource files, such as Jar packages, are generally read-only. This org.my.path is the package path where resdb is located

In addition, after the jdbc-url, if ifexists=true is not specified, a new database will be created automatically if the connected database does not exist. When username and password are not specified, the default SA and empty password are used.

3. Memory (Memory-Only) mode

All databases are completed in memory, and if the program exits, the corresponding databases are also destroyed at the same time. The way to create or connect to the database is the same as the process mode, except that the jdbc-url is: jdbc:hsqldb:mem: database table name

4. Summary

Through the three modes mentioned above, you can obtain a database connection Connection, and obtain the Statement from the Connection, then you can execute SQL statements through the Statement, thereby adding, deleting, modifying and querying the database.

Four HSQLDB database driver

The HSQLDB JDBC driver (corresponding class name: org.hsqldb.jdbcDriver) is provided in Hsqldb.jar to provide access to database files. Generally, the default port number is 9001. Usually you need to configure this class into the project through the .properties file

jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://localhost:9001/xbook
jdbc.username=sa
jdbc.password=

Or directly load the JDBC driver class through code.

        //1.初始化JDBC驱动
        try {
          
            Class.forName("org.hsqldb.jdbcDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("ERROR:failed to load jdbc driver");
            return;
        }

Then according to the engine mode of different databases, use the corresponding jdbc-url to access the database files.

Five HSQLDB database user operation interface

Of course, HSQLDB also provides some user-operable interfaces to help operate the database.

1. Configure HSQLDB database tools

org.hsqldb.util.DatabaseManager and org.hsqldb.util.DatabaseManagerSwing, both of which can configure and manage the database, with different interfaces. In the command window (if you are currently creating a database in server mode, you need to reopen a command window to execute the command), you can open these two tools directly by running hsqldb.jar, and then you can use the interface The operation interface is up. There are usually the following operations:

  • (1) The corresponding Type needs to be selected according to the database engine mode set, and the alias of the database that needs to be operated is set after the URL

Note that setting the User and Password here will report an error. Later, I will see how to set the User and Password. User defaults to SA and Password is empty.

  • (2) If you are familiar with the SQL statement, you can directly enter it in the input box on the right. If you are not familiar with the SQL statement, you can use the template example provided in Common or right-click the corresponding table to automatically add the SQL statement.

  • (3) When the SQL statement is executed successfully, it will display as shown in the figure:

 Through this tool, you can easily add, delete, modify and check the database.

2. Other tools

In the official API documentation, the following tools are also provided:

org.hsqldb.util.Transfer

org.hsqldb.util.QueryTool

org.hsqldb.util.SqlTool

Six summary

Through the above part, I briefly understood the basic knowledge of HSQLDB, and briefly summarized:

1. HSQLDB includes database engine, database driver and user-operable interface tools;

2. HSQLDB does not need to be installed, just download the latest .zip from the official website, unzip it and place it in any directory on your computer;

3. The HSQLDB database engine is divided into three modes: server mode, memory mode and process mode;

(1) The server mode is to run the database in a separate JVM, which is divided into Server mode, WebServer mode, and Servlet mode;

  • Server mode uses HSQLDB proprietary communication protocol, the corresponding startup class is org.hsqldb.server, jdbc-url: jdbc:hsqldb:hsql://localhost/ database alias
  • WebServer mode uses HTTP for communication, and the corresponding startup class is org.hsqldb.server.WebServer, jdbc-url: jdbc:hsqldb:http://localhost/ database alias
  • The Servlet mode is similar to the WebServer mode, except that the Servlet mode allows the application server of the Servlet container to access the database

(2) In memory mode, the created database can only run in memory. When the application is closed, the corresponding database data is also destroyed. When the database is created through Connection, the jdbc-url is: jdbc:hsqldb:mem:database Table Name

(3) The process mode is that the created database runs in the application process, and the database will exist in the form of a file. When the application is closed, the database still exists, but when the application is running, only the current application can access the database , None of the others can be accessed

4. HSQLDB also provides a database driver: org.hsqldb.jdbcDriver, which can be loaded through code or configuration files, so that applications can access HSQLDB database files;

5. HSQLDB also provides the DatabaseManager and DatabaseManagerSwing of the user operation interface to allow users to operate the database. The functions of the two are the same, but the interface is different;

Later, let’s take a look at how to set the user name and password and through a java instance, the system will take a look at the process of application access to the database, see Xiaobai novice web development simple summary (8)-database HSQLDB instance

Guess you like

Origin blog.csdn.net/nihaomabmt/article/details/113995051