Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在哪里可以看到HSQL数据库和表_Java_Jdbc_Hsqldb - Fatal编程技术网

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

Java 在哪里可以看到HSQL数据库和表,java,jdbc,hsqldb,Java,Jdbc,Hsqldb,我已经下载了一个hsqldb.jar,并设置为projectbuildpath,接下来我编写了这个程序 Class.forName("org.hsqldb.jdbc.JDBCDriver"); Connection conn = DriverManager.getConnection( "jdbc:hsqldb:mem:mydb", "SA", ""); String bookTableSQL = "create table MY_TABLE ("

我已经下载了一个hsqldb.jar,并设置为projectbuildpath,接下来我编写了这个程序

  Class.forName("org.hsqldb.jdbc.JDBCDriver");
Connection conn = DriverManager.getConnection(
                     "jdbc:hsqldb:mem:mydb", "SA", "");

String bookTableSQL = "create table MY_TABLE ("+
" TITLE varchar(256) not null primary key,"+
" AUTHOR varchar(256) not null"+
");";

Statement st = conn.createStatement();
st.execute(bookTableSQL);
System.out.println(st);
String sql = "INSERT INTO MY_TABLE " +
"VALUES ('Mahnaz', 'Fatma')";

st.executeUpdate(sql);
已成功创建数据库和表。在下一步中,我插入了一个示例数据,并得到显示的数据

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);

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

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

如果要使其持久化,请修复连接创建:将mem替换为文件。大概是这样的:

Connection conn = DriverManager.getConnection("jdbc:hsqldb:file:mydb", "sa", "");
您可以阅读不同的HSQLDB模式。您还可以指定数据库存储文件的路径:

jdbc:hsqldb:file:/file/path/to/test"
第一次运行后,HSQLDB将创建几个文件。您可以读取的每个文件的用途

测试属性 包含条目“已修改”。如果条目“modified”设置为“yes”,则数据库正在运行或未正确关闭(因为关闭算法在末尾将“modified”设置为“no”)

测试脚本 此文件包含构成数据库直到最后一个检查点的SQL语句-它与test.backup同步

测试数据 此文件仅包含缓存表的(二进制)数据记录

测试备份 这是压缩文件,包含上次检查点时旧test.data文件的完整备份

测试日志 此文件包含自上一个检查点以来修改数据库的额外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

或者您可以使用流行的工具,如。

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

AbstractTestDao:

公共抽象类AbstractTestDao{
/**
*将实体持久化到数据库中的通用方法。
*
*@param entity Java对象,来自用@entity注释的(hibernate)类
*/
无效实体(T实体){
Session Session=HibernateUtil.getSessionFactory().openSession();
会议(实体);
session.beginTransaction().commit();
session.close();
}
/**
*从数据库检索实体的通用方法。
*
*@param cls对象类
*@param id实体唯一标识符(主键)
*@return从数据库中转换实体对象
*/
T getEntityById(类cls,长id){
Session Session=HibernateUtil.getSessionFactory().openSession();
T entity=cls.cast(session.load(cls,id));
session.close();
返回实体;
}
/**
*别忘了关闭连接,这样内存数据库中的用户就可以释放it资源了。
*
*@return连接对象到内存中的db HyperSQL。
*@SQLException
*/
公共静态连接getNewConn()引发SQLException{
返回DriverManager.getConnection(“jdbc:hsqldb:mem:testdb;shutdown=false”、“SA”和“);
}   
/**
*从当前内存中的数据库生成脚本,并将txt文件放在目录中。
*该脚本描述mem db中的当前值,包括约束。
*
*@param testName表示用于描述文件的junit测试名称的字符串。
*@SQLException
*/
void createDatabaseScript(最终字符串testName)引发SQLException{
最终字符串filePath=新文件(“”).getAbsolutePath();
最后一个字符串targetDir=“/target/Temp/Databasedump/”;
最终字符串directoryPath=filePath.concat(targetDir);
最终文件目录=新文件(目录路径);
如果(!directory.exists()){
mkdir()目录;
}
最终字符串文件名=uniqueFileNameGenerator(directoryPath,testName);
最终连接conn=getNewConn();
语句st=null;
结果集rs=null;
试一试{
st=conn.createStatement();
//示例:st.executeQuery(“脚本“../Temp/dump4.txt”)
最终字符串sqlStatement=String.format(“脚本'%s%s',目录路径,文件名”);
rs=st.executeQuery(sqlStatement);
}最后{
如果(st!=null){
圣克洛斯();
}
如果(rs!=null){
rs.close();
}
如果(conn!=null){
康涅狄格州关闭();
}
}               
}
/**
*在一个目录中搜索一个唯一的文件名,每个日期的可能性为1到2147483647(Integer.MAX_VALUE)。
*如果给出了所有2147483646文件名,可能会抛出StackOverflower错误。
*
*@param directoryPath-表示要使用的目录的字符串。
*@param name-表示要使用的文件名的字符串。
*@表示唯一文件名的返回字符串
*/
专用字符串UniqueFileName生成器(最终字符串目录路径,最终字符串名称){
最终日期格式DateFormat=新的简化格式(“yyyy-MM-dd”);
最后一个字符串todayDate=dateFormat.format(Calendar.getInstance().getTime());
最终整数randomNumber=(int)(Math.random()*Integer.MAX_值+1);
最终字符串文件名=名称+“\u”+今天日期+“\u”+随机数+“.txt”;
文件文件=新文件(目录路径+文件名);
if(file.exists()){
返回uniqueFileNameGenerator(目录路径,名称);
}
返回文件名;
}   
}

HSQL数据库版本:


hsqldb
hsqldb
1.8.
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;
    }   
}
<dependency>
    <groupId>hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>1.8.0.10</version>
</dependency>