我正在尝试在内存中的 sqlite 数据库上创建一个表。我有一个名为 createTable
的方法来创建一个表,该表使用 getConnection
方法初始化与数据库的连接。
创建表:
private void createTable() {
try {
final Connection connection = getConnection();
final Statement statement = connection.createStatement();
statement.execute(
"CREATE TABLE videos (id INTEGER PRIMARY KEY, title VARCHAR(255), description TEXT, path TEXT, category VARCHAR(255), published INTEGER DEFAULT 0, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP);");
statement.close();
connection.close();
} catch (final SQLException e) {
LOGGER.warn("Failed to create table.", e);
}
}
获取连接
private static Connection getConnection() {
try {
Class.forName("org.sqlite.JDBC");
return DriverManager.getConnection("jdbc:sqlite:");
} catch (final Exception e) {
LOGGER.warn("Failed to get connection.", e);
throw new RuntimeException(e);
}
}
为了测试数据库,我写了一个简单的insert
方法:
public void insert() {
try {
final Connection connection = getConnection();
final Statement statement = connection.createStatement();
statement.executeUpdate(
"INSERT INTO videos (title, path, category) VALUES ('test title', 'test path', 'test category');");
statement.close();
connection.close();
} catch (final SQLException e) {
LOGGER.warn("Failed to insert.", e);
}
}
当我这样做
this.createTable();
this.insert();
我收到以下错误:
2017-09-17 22:38:02 WARN Database:128 - Failed to insert.
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: videos)
at org.sqlite.core.DB.newSQLException(DB.java:909)
at org.sqlite.core.DB.newSQLException(DB.java:921)
at org.sqlite.core.DB.throwex(DB.java:886)
at org.sqlite.core.NativeDB._exec_utf8(Native Method)
at org.sqlite.core.NativeDB._exec(NativeDB.java:87)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)...
对于连接,我使用的是 org.xerial:sqlite-jdbc 的 v3.20.0
。
为什么没有创建表的任何想法?我没有看到任何异常或任何东西。 SQLFiddle for the example above好像没问题。
最佳答案
如果我阅读 the documentation正确地,默认情况下数据库仅存在于其数据库连接中:
Instead, a new database is created purely in memory. The database ceases to exist as soon as the database connection is closed. Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases.
最简单的解决方法是不打开第二个连接,而是继续使用您用于为其他数据库查询创建表的连接。
如果要打开多个连接,可以在数据库url上设置?cache=shared
参数。
关于java - 无法在内存中的 sqlite 数据库上创建表,没有任何错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46272298/