我正在尝试在内存中的sqlite数据库上创建一个表。我有一个名为createTable
的方法来创建一个表,该表使用getConnection
方法初始化与数据库的连接。
CREATETABLE:
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);
}
}
的getConnection
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 ' s v 3.20.0
的连接。
为什么没有创建表的任何想法?我没有看到任何例外或任何事情。 SQLFiddle for the example above似乎很好。
答案 0 :(得分:3)
如果我正确读取the documentation,则默认情况下数据库仅存在于其数据库连接中:
相反,新的数据库纯粹在内存中创建。数据库连接关闭后,数据库就不再存在。 Every:memory:数据库彼此不同。因此,打开两个数据库连接,每个连接都有文件名":memory:"将创建两个独立的内存数据库。
最简单的解决方法是不打开第二个连接,但继续使用您为其他数据库查询创建表的连接。
如果要打开多个连接,可以在数据库URL上设置?cache=shared
参数。