About HSQLDB in SAP Commerce Cloud development environment

In the SAP Commerce Cloud local installation documentation, HSQLDB is mentioned:

HSQLDB (Hypersonic SQL Database) is an open source relational database management system (RDBMS). It is written entirely in Java, supports the SQL standard, and provides high-performance and embedded database functions. HSQLDB is lightweight, fast, easy to use and has broad compatibility, making it widely used in various application scenarios. This article will introduce in detail the characteristics and usage of HSQLDB and demonstrate its functions through examples.

Features of HSQLDB

1. Embedded database

One of the most notable features of HSQLDB is its embedded database functionality. This means you can embed HSQLDB into Java applications without the need for an additional database server or separate installation process. This lightweight deployment method makes HSQLDB very useful in small application and prototype development.

2. Support SQL standard

HSQLDB follows SQL standards, so it is very compatible with other mainstream RDBMS (such as MySQL, PostgreSQL, Oracle, etc.). This means you can use common SQL syntax and queries to migrate existing databases to HSQLDB or from HSQLDB to other database systems without making too many modifications.

3. In-memory database

HSQLDB allows you to store the database entirely in memory, this mode is called an in-memory database. In-memory databases are ideal for temporary data storage that require high-speed read and write operations, such as test environments or certain compute-intensive applications.

4. Support persistent storage

Although HSQLDB supports in-memory databases, it also allows data to be persisted to disk to ensure long-term preservation of data. This makes HSQLDB also very promising for use in production environments.

5. Support multiple connection methods

HSQLDB supports multiple connection methods, including JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity), so it can be integrated with various programming languages ​​and tools, such as Java, Python, Ruby, etc.

6. Support transaction processing

HSQLDB supports ACID (Atomicity, Consistency, Isolation, Durability) transaction properties, which makes it suitable for applications that require strong consistency and data integrity.

7. Open source and free

HSQLDB is open source software, released under the GNU General Public License (GPL), which means you can use, modify and distribute it for free without worrying about high licensing fees.

HSQLDB usage

1. Database creation and connection

To start using HSQLDB, you first need to create a database and establish a connection. Here is a sample code using Java that demonstrates how to create an in-memory database and connect to it:

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

public class HSQLDBExample {
    
    
    public static void main(String[] args) {
    
    
        Connection connection = null;
        try {
    
    
            // 注册HSQLDB的JDBC驱动程序
            Class.forName("org.hsqldb.jdbc.JDBCDriver");
            
            // 创建连接(内存数据库)
            connection = DriverManager.getConnection("jdbc:hsqldb:mem:testdb", "SA", "");
            
            // 执行数据库操作
            // ...
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (connection != null) {
    
    
                try {
    
    
                    connection.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

In the above example, we first registered the JDBC driver for HSQLDB and then created an in-memory database connection. The connection string "jdbc:hsqldb:mem:testdb"specifies the type (in-memory database) and name of the database, as well as the username and password.

2. Create table and insert data

Next, let's create a table and insert some data. The following is an example that demonstrates how to create a table and insert data using SQL statements:

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

public class HSQLDBExample {
    
    
    public static void main(String[] args) {
    
    
        Connection connection = null;
        try {
    
    
            Class.forName("org.hsqldb.jdbc.JDBCDriver");
            connection = DriverManager.getConnection("jdbc:hsqldb:mem:testdb", "SA", "");
            
            // 创建表
            String createTableSQL = "CREATE TABLE employees (id INT, name VARCHAR(255))";
            PreparedStatement createTableStatement = connection.prepareStatement(createTableSQL);
            createTableStatement.executeUpdate();
            
            // 插入数据
            String insertDataSQL = "INSERT INTO employees (id, name) VALUES (?, ?)";
            PreparedStatement insertDataStatement = connection.prepareStatement(insertDataSQL);
            
            insertDataStatement.setInt(1, 1);
            insertDataStatement.setString(2, "John Doe");
            insertDataStatement.executeUpdate();
            
            insertDataStatement.setInt(1, 2);
            insertDataStatement.setString(2, "Jane Smith");
            insertDataStatement.executeUpdate();
            
            // 执行其他数据库操作
            // ...
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (connection != null) {
    
    
                try {
    
    
                    connection.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

In this example, we first create a table called "employees" that contains two columns: id and name. Then, we inserted two rows of data using prepared statements.

3. Query data

HSQLDB supports standard SQL query statements, and you can use these query statements to retrieve data. Here's an example of how to query previously inserted data:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class HSQLDBExample {
    
    
   

 public static void main(String[] args) {
    
    
        Connection connection = null;
        try {
    
    
            Class.forName("org.hsqldb.jdbc.JDBCDriver");
            connection = DriverManager.getConnection("jdbc:hsqldb:mem:testdb", "SA", "");
            
            // 执行查询
            String querySQL = "SELECT id, name FROM employees";
            PreparedStatement queryStatement = connection.prepareStatement(querySQL);
            ResultSet resultSet = queryStatement.executeQuery();
            
            // 处理查询结果
            while (resultSet.next()) {
    
    
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }
            
            // 执行其他数据库操作
            // ...
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (connection != null) {
    
    
                try {
    
    
                    connection.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

In this example, we execute a simple SELECT query and iterate through the result set to get the data for the query.

Sample Application: Task Manager Based on HSQLDB

Let's create a sample application to implement a simple task manager using HSQLDB. This app will allow users to add, edit, and delete tasks, as well as view a list of tasks.

Database Design

First, we need to define the data model of the task. We will create a table called "tasks" with the following columns:

  • id: unique identifier for the task (integer)
  • title: the title of the task (string)
  • description: description of the task (string)
  • due_date: task's due date (date)

Application features

  1. Add a task: Users can enter a title, description and due date for the task and add the task to the database.
  2. Edit tasks: Users can select a task and edit its title, description, or due date.
  3. Delete Task: User can select a task and delete it from the database.
  4. View task list: Users can view all tasks and sort them by due date.

Implementation example

Here is a simplified Java example demonstrating how to implement the above functionality:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class TaskManager {
    
    
    public static void main(String[] args) {
    
    
        Connection connection = null;
        try {
    
    
            Class.forName("org.hsqldb.jdbc.JDBCDriver");
            connection = DriverManager.getConnection("jdbc:hsqldb:mem:taskdb", "SA", "");
            
            // 创建任务表
            String createTableSQL = "CREATE TABLE tasks (id INT IDENTITY, title VARCHAR(255), description VARCHAR(255), due_date DATE)";
            PreparedStatement createTableStatement = connection.prepareStatement(createTableSQL);
            createTableStatement.executeUpdate();
            
            Scanner scanner = new Scanner(System.in);
            
            while (true) {
    
    
                System.out.println("任务管理器");
                System.out.println("1. 添加任务");
                System.out.println("2. 编辑任务");
                System.out.println("3. 删除任务");
                System.out.println("4. 查看任务列表");
                System.out.println("5. 退出");
                System.out.print("请选择操作(1/2/3/4/5):");
                
                int choice = scanner.nextInt();
                
                switch (choice) {
    
    
                    case 1:
                        addTask(connection, scanner);
                        break;
                    case 2:
                        editTask(connection, scanner);
                        break;
                    case 3:
                        deleteTask(connection, scanner);
                        break;
                    case 4:
                        viewTaskList(connection);
                        break;
                    case 5:
                        System.out.println("谢谢使用,再见!");
                        return;
                    default:
                        System.out.println("无效的选项,请重新选择。");
                }
            }
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (connection != null) {
    
    
                try {
    
    
                    connection.close();
                } catch (SQLException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }

    private static void addTask(Connection connection, Scanner scanner) throws SQLException {
    
    
        System.out.print("请输入任务标题:");
        String title = scanner.next();
        System.out.print("请输入任务描述:");
        String description = scanner.next();
        System.out.print("请输入截止日期(YYYY-MM-DD):");
        String dueDate = scanner.next();
        
        String insertSQL = "INSERT INTO tasks (title, description, due_date) VALUES (?, ?, ?)";
        PreparedStatement insertStatement = connection.prepareStatement(insertSQL);
        insertStatement.setString(1, title);
        insertStatement.setString(2, description);
        insertStatement.setString(3, dueDate);
        insertStatement.executeUpdate();
        
        System.out.println("任务已添加!");
    }

    private static void editTask(Connection connection, Scanner scanner) throws SQLException {
    
    
        viewTaskList(connection);
        System.out.print("请选择要编辑的任务(输入任务ID):");
        int taskId = scanner.nextInt();
        
        System.out.print("请输入新的任务标题:");
        String title = scanner.next();
        System.out.print("请输入新的任务描述:");
        String description = scanner.next();
        System.out.print("请输入新的截止日期(YYYY-MM-DD):");
        String dueDate = scanner.next();
        
        String updateSQL = "UPDATE tasks SET title = ?, description = ?, due_date = ? WHERE id = ?";
        PreparedStatement updateStatement = connection.prepareStatement(updateSQL);
        updateStatement.setString(1, title);
        updateStatement.setString(2, description);
        updateStatement.setString(3, dueDate);
        updateStatement.setInt(4, taskId);
        updateStatement.executeUpdate();
        
        System.out.println("任务已编辑!");
    }

    private static void deleteTask(Connection connection, Scanner scanner) throws SQLException {
    
    
        viewTaskList(connection);
        System.out.print("请选择要删除的任务(输入任务ID):");
        int taskId = scanner.nextInt();
        
        String deleteSQL = "DELETE FROM tasks WHERE id = ?";
        PreparedStatement deleteStatement = connection.prepareStatement(deleteSQL);
        deleteStatement.setInt(1, taskId);
        deleteStatement.executeUpdate();
        
        System.out.println("任务已删除!");
    }

    private static void viewTaskList(Connection connection) throws SQLException {
    
    
        System.out.println("任务列表:");
        String querySQL = "SELECT id, title, description, due_date FROM tasks ORDER BY due_date";
        PreparedStatement queryStatement = connection.prepareStatement(querySQL);
        ResultSet resultSet = queryStatement.executeQuery();
        
        while (resultSet.next()) {
    
    
            int id = resultSet.getInt("id");
            String title = resultSet.getString("title");
            String description = resultSet.getString("description");
            String dueDate = resultSet.getString("due_date");
            System.out.println("ID: " + id + ", 标题: " + title + ", 描述: "

 + description + ", 截止日期: " + dueDate);
        }
    }
}

This sample application uses HSQLDB to store task information and provides a command line interface that allows users to perform various task management operations. You can extend and improve this application as needed.

in conclusion

HSQLDB is a powerful and versatile relational database management system. It has the characteristics of embedded, lightweight, high performance and compatibility, and is very suitable for various application scenarios. Through the introduction and examples in this article, you have learned the basic features, usage and how to create a simple application program of HSQLDB. Whether in embedded systems or large-scale applications, HSQLDB can provide a viable solution for your data storage needs.

Guess you like

Origin blog.csdn.net/i042416/article/details/132778693