我正在使用 java 中的 SQLite JDBC 驱动程序 3.7.2 将一些数据写入数据库文件。当我尝试在命令行上打开数据库文件时,我收到一条错误消息:
“无法打开数据库 test.db:文件已加密或不是数据库”
我做了一个导致这种行为的最小示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class PlaygroundSQLite {
public static void insertIntoDB(String dbFilename, String tablename){
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:"+dbFilename);
PreparedStatement prep = conn.prepareStatement("insert into " + tablename + "( id, text) values (?, ?);");
prep.setString(1, "1FD22A38");
prep.setString(2, "This is a simple test");
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void createDB(String dbFilename, String tablename){
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + dbFilename);
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists test;");
stat.executeUpdate("create table " + tablename + " (key INTEGER PRIMARY KEY, id TEXT , text TEXT);");
conn.close();
stat.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String dbFilename = "test.db";
String tablename = "test";
PlaygroundSQLite.createDB(dbFilename, tablename);
PlaygroundSQLite.insertIntoDB(dbFilename, tablename);
}
}