我在哪里可以看到HSQL数据库和表

时间:2016-02-06 10:37:15

标签: java jdbc hsqldb

我已经下载了一个hsqldb.jar并设置为项目构建路径,然后我编写了该程序

String sqlsel = "SELECT TITLE,AUTHOR FROM MY_TABLE";
 ResultSet rs = st.executeQuery(sqlsel);
 //STEP 5: Extract data from result set
 while(rs.next()){
    //Retrieve by column name
     String id  = rs.getString("TITLE");
     String age = rs.getString("AUTHOR");

    //Display values
    System.out.print("ID: " + id);
    System.out.print(", Age: " + age);

 }

数据库和表格已成功创建。在下一步中,我插入了一个示例数据并显示数据

url=/users/*

我的问题是我没有创造" mydb"数据库。 另外在哪里可以看到创建的数据库和表?

2 个答案:

答案 0 :(得分:5)

您已在内存中创建了数据库,因此您的表/数据没有持久性文件,然后关闭应用程序,丢失所有数据。

如果您想持续修复连接,请执行以下操作:将 mem 替换为文件。像这样:

Connection conn = DriverManager.getConnection("jdbc:hsqldb:file:mydb", "sa", "");

您可以阅读有关不同HSQLDB模式here的信息。您还可以指定数据库将存储文件的路径:

jdbc:hsqldb:file:/file/path/to/test"

首次运行后,HSQLDB将创建多个文件。您可以阅读的每个文件的用途here

  

<强> test.properties   包含“已修改”条目。如果条目'modified'设置为'yes',则数据库正在运行或未正确关闭(因为close算法在结尾处将'modified'设置为'no'。

     

<强> test.script   此文件包含组成数据库直到最后一个检查点的SQL语句 - 它与test.backup同步。

     

<强> test.data   此文件仅包含CACHED表的(二进制)数据记录。

     

<强> test.backup   这是压缩文件,包含上次检查点时旧test.data文件的完整备份。

     

<强> test.log中   此文件包含自上一个检查点以来修改过数据库的额外SQL语句(类似于“重做日志”或“事务日志”,但只是文本)。

顺便说一句,您可以使用此查询获取所有表格:

SELECT * FROM INFORMATION_SCHEMA.SYSTEM_TABLES where TABLE_TYPE='TABLE'

您可以将此查询作为普通查询执行:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM INFORMATION_SCHEMA.SYSTEM_TABLES where TABLE_TYPE='TABLE'");

while(rs.next()) {
    ...
}

您还可以使用内置管理器查看数据库。您可以开始使用命令:

java -cp /path/to/hsqldb.jar org.hsqldb.util.DatabaseManager 

然后指定数据库的路径:

jdbc:hsqldb:file:mydb

或者您可以使用SQuirreL等热门工具。

答案 1 :(得分:0)

您可以转储HSQL内存数据库。

<强> AbstractTestDao:

public abstract class AbstractTestDao {

    /**
     * Generic method for persisting entities into database.
     *
     * @param entity Java object from a (hibernate) class annotated with @Entity
     */
    <T> void persistEntity(T entity) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.persist(entity);
        session.beginTransaction().commit();
        session.close();
    }

    /**
     * Generic method for retrieving entities from database.
     *
     * @param cls Object class
     * @param id  Entity unique identifier (Primary Key)
     * @return Casted Entity object from db
     */
    <T> T getEntityById(Class<T> cls, Long id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        T entity = cls.cast(session.load(cls, id));
        session.close();
        return entity;
    }

    /**
     * Don't forget to close your connection so that the in-mem db can release it resources.
     *
     * @return Connection object to the in-memory db HyperSQL.
     * @throws SQLException
     */
    public static Connection getNewConn() throws SQLException {
        return DriverManager.getConnection("jdbc:hsqldb:mem:testdb;shutdown=false", "SA", "");
    }   

    /**
     * Makes a script from the current in-memory database and place a txt file in a directory.
     * The script describes the current in-mem db including constrains.
     *
     * @param testName A String representing the junit test name used for describing the file.
     * @throws SQLException
     */
    void createDatabaseScript(final String testName) throws SQLException {

        final String filePath = new File("").getAbsolutePath();
        final String targetDir = "/target/Temp/Databasedump/";
        final String directoryPath = filePath.concat(targetDir);
        final File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdir();
        }

        final String fileName = uniqueFileNameGenerator(directoryPath, testName);

        final Connection conn = getNewConn();
        Statement st = null;
        ResultSet rs = null;

        try {
            st = conn.createStatement();
            //Example: st.executeQuery("SCRIPT '../Temp/dump4.txt'")
            final String sqlStatement = String.format("SCRIPT '%s%s'", directoryPath, fileName);
            rs = st.executeQuery(sqlStatement);

        } finally {
            if (st != null) {
                st.close();
            }
            if (rs != null) {
                rs.close();
            }
            if (conn != null) {
                conn.close();
            }
        }               
    }

    /**
     * Search for a unique filename in a directory with 1 to 2147483647 (Integer.MAX_VALUE) possibilities per date.
     * May throw a StackOverflowError if all 2147483646 file names are given away.
     *
     * @param directoryPath - String representing the directory you want to use.
     * @param name          - String representing the filename you want to use.
     * @return String representing a unique filename
     */
    private String uniqueFileNameGenerator(final String directoryPath, final String name) {

        final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        final String todayDate = dateFormat.format(Calendar.getInstance().getTime());
        final Integer randomNumber = (int) (Math.random() * Integer.MAX_VALUE + 1);
        final String fileName = name + "_" + todayDate + "_" + randomNumber + ".txt";

        File file = new File(directoryPath + fileName);

        if (file.exists()) {
            return uniqueFileNameGenerator(directoryPath, name);
        }
        return fileName;
    }   
}


HSQL数据库版本:

<dependency>
    <groupId>hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>1.8.0.10</version>
</dependency>