【发布时间】:2021-06-16 23:31:46
【问题描述】:
我有一个使用 SqlLite 数据库的 ToDo 应用程序,我想通过创建我的应用程序名称的文件夹来创建我的 SqlLite 数据库的 .db 文件并将其保存在我的内部存储中。 我不知道该怎么做。 谢谢。
【问题讨论】:
-
您是否研究/尝试过我们可以帮助您解决的任何问题?
我有一个使用 SqlLite 数据库的 ToDo 应用程序,我想通过创建我的应用程序名称的文件夹来创建我的 SqlLite 数据库的 .db 文件并将其保存在我的内部存储中。 我不知道该怎么做。 谢谢。
【问题讨论】:
你必须
如果使用 WAL 作为 Android 9+ 的默认日志记录模式,则这需要完全提交数据库。如果使用日记模式,这无关紧要。见:-
getDatabasePath(<database_name>) 方法将返回文件,您可以使用 File 的 getAbsolutePath()(或 getCanonicalPath() 方法从中获取路径。参见 -李>
使用 File 的 mkDir 或 mkDirs 方法创建要存储数据的目录/文件夹。
将文件复制到存储位置路径。
这是用于备份数据库的代码的摘录(如果数据库使用 WAL,它将提交(检查点)):-
String dbfilename = context.getDatabasePath(<the database name>).getPath();
try {
checkpointIfWALEnabled(context);
FileInputStream fis = new FileInputStream(dbfile);
OutputStream backup = new FileOutputStream(<path to storage location (assumes directories exist)>);
byte[] buffer = new byte[32768];
int length;
while ((length = fis.read(buffer)) > 0) {
backup.write(buffer, 0, length);
}
backup.flush();
backup.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
<the database name> 和 <path to storage location (assumes directories exist)> 必须相应更改。有:-
private void checkpointIfWALEnabled(Context context) {
Cursor csr;
int wal_busy = -99, wal_log = -99, wal_checkpointed = -99;
SQLiteDatabase db = SQLiteDatabase.openDatabase(context.getDatabasePath(<the database name>).getPath(), null, SQLiteDatabase.OPEN_READWRITE);
csr = db.rawQuery("PRAGMA journal_mode", null);
if (csr.moveToFirst()) {
String mode = csr.getString(0);
if (mode.toLowerCase().equals("wal")) {
csr = db.rawQuery("PRAGMA wal_checkpoint", null);
if (csr.moveToFirst()) {
wal_busy = csr.getInt(0);
wal_log = csr.getInt(1);
wal_checkpointed = csr.getInt(2);
}
csr = db.rawQuery("PRAGMA wal_checkpoint(TRUNCATE)", null);
csr.getCount();
csr = db.rawQuery("PRAGMA wal_checkpoint", null);
if (csr.moveToFirst()) {
wal_busy = csr.getInt(0);
wal_log = csr.getInt(1);
wal_checkpointed = csr.getInt(2);
}
}
csr.close();
db.close(); // Should checkpoint the database anyway.
}
【讨论】: