SQLite 没有立即插入记录

SQLite not inserting record instantly

我正在开发一个在收到付款后将交易保存在 SQLite 数据库中的应用程序。 一旦交易获得批准,它就会被插入数据库,然后向该用户显示批准。 当我得到结果时,我表示同意 sqlitedatabase.insert() 方法,并检查它 returns 行号。

public static boolean insert(String tableName, SQLiteDatabase sqLiteDatabase, ContentValues contentValues){
        long rowId = sqLiteDatabase.insert(tableName, null, contentValues);
        return rowId != -1;
    }

问题是,当向用户显示批准时,我通过弹出电池来关闭设备(我正在测试电池盒)并且 当我重新启动设备时,我看到 没有记录被插入 到数据库中。这让我觉得 SQLite 在返回行 ID 后异步插入记录。

我正在使用 AsyncTask 并在 doInBackground 中插入,并在 AsyncTask 的 onPostExecute() 中显示用户批准。

我的问题是,有什么方法可以确保在我调用插入方法时插入记录,或者我在这里做错了什么?

经过一些研究,我意识到是什么导致了这个问题。 这是 SQLite 的默认配置设置,同步设置不是 FULL。根据documentation:

FULL (2) When synchronous is FULL (2), the SQLite database engine will use the xSync method of the VFS to ensure that all content is safely written to the disk surface prior to continuing. This ensures that an operating system crash or power failure will not corrupt the database. FULL synchronous is very safe, but it is also slower. FULL is the most commonly used synchronous setting when not in WAL mode.

默认配置不完整,我在我的 SQLiteOpenHelper class' onConfigure 回调中更改了它。它解决了这个问题。

@Override
public void onConfigure(SQLiteDatabase db) {
    db.execSQL("PRAGMA synchronous = 2");
}

尽管文档指出 "FULL synchronous is very safe, but it is also slower.",尽管在某些情况下进行了批量插入,但我没有发现明显的性能差异。