H2内存数据库将数据存储在JVM内部的内存中。当JVM退出时,这些数据就丢失了。
我怀疑您正在做的事情与下面的两个Java类类似。其中一个类创建了一个表,而另一个类尝试插入表:
import java.sql.*;
public class CreateTable {
public static void main(String[] args) throws Exception {
DriverManager.registerDriver(new org.h2.Driver());
Connection c = DriverManager.getConnection("jdbc:h2:mem:test");
PreparedStatement stmt = c.prepareStatement("CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64))");
stmt.execute();
stmt.close();
c.close();
}
}
and
import java.sql.*;
public class InsertIntoTable {
public static void main(String[] args) throws Exception {
DriverManager.registerDriver(new org.h2.Driver());
Connection c = DriverManager.getConnection("jdbc:h2:mem:test");
PreparedStatement stmt = c.prepareStatement("INSERT INTO PERSON (ID, FIRSTNAME, LASTNAME) VALUES (1, 'John', 'Doe')");
stmt.execute();
stmt.close();
c.close();
}
}
当我一个接一个地运行这些类时,我得到了以下输出:
C:\Users\Luke\stuff>java CreateTable
C:\Users\Luke\stuff>java InsertIntoTable
Exception in thread "main" org.h2.jdbc.JdbcSQLException: Table "PERSON" not found; SQL statement:
INSERT INTO PERSON (ID, FIRSTNAME, LASTNAME) VALUES (1, 'John', 'Doe') [42102-154]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
at org.h2.message.DbException.get(DbException.java:167)
at org.h2.message.DbException.get(DbException.java:144)
...
一旦第一个java进程退出,由CreateTable创建的表就不再存在。因此,当InsertIntoTable类出现时,没有供它插入的表。
当我将连接字符串更改为jdbc:h2:test时,我发现没有这样的错误。我还发现出现了一个文件test.h2.db。这是H2放置表的位置,因为它存储在磁盘上,所以表仍然在那里,供InsertIntoTable类查找。