我已经下载了一个hsqldb.jar并设置了项目构建路径,然后接下来我编写了程序
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 将创建多个文件。您可以在此处阅读每个文件的用途。
test.properties 包含条目"已修改"。如果条目"modified"设置为"yes",则数据库正在运行或未正确关闭(因为关闭算法在末尾将"modified"设置为"no"(。
test.script 此文件包含构成数据库的 SQL 语句,直到最后一个检查点 - 它与 test.backup 同步。
测试数据 此文件仅包含缓存表的(二进制(数据记录。
测试.备份 这是压缩文件,其中包含上次检查点时旧 test.data 文件的完整备份。
测试.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。
您可以转储内存中的 HSQL 数据库。
摘要测试道:
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>