gpt4 book ai didi

android - 关于SQLite 3,是否需要先写后读?

转载 作者:搜寻专家 更新时间:2023-11-01 09:20:00 25 4
gpt4 key购买 nike

在一个Android应用中,关于SQLITE3,
是否需要先写后读,还是我们可以指望交易成功?

更新以显示插入数据的函数:

    // Insert a post into the database
public void addM0(Store_M0_DataClass mStore_M0_DataClass)
{
// Create and/or open the database for writing
SQLiteDatabase db = getWritableDatabase();



// It's a good idea to wrap our insert in a transaction. This helps with performance and ensures
// consistency of the database.
db.beginTransaction();
try
{
// The user might already exist in the database (i.e. the same user created multiple posts).

ContentValues values = new ContentValues();
values.put(KEY_M0_ID, mStore_M0_DataClass.getM0_ID());
values.put(KEY_M0_IMAGE1, mStore_M0_DataClass.getM0_Image1());
values.put(KEY_M0_IMAGE2, mStore_M0_DataClass.getM0_Image2());
values.put(KEY_M0_ENABLE, mStore_M0_DataClass.getM0_Enable());

db.insertOrThrow(TABLE_M0, null, values);

db.setTransactionSuccessful();
}
catch (Exception e)
{
}
finally
{
db.endTransaction();
}
}

最佳答案

插入或任何单个操作会自动包含在事务中,因此将其包装在事务中没有任何好处。但是,如果您在一个循环中执行多个插入,那么在循环之前开始一个事务,将其设置为成功,如果成功,在循环之后,并在循环之后结束事务,这将有好处。

除非您想捕获异常,否则几乎不需要使用 insertOrThrow,因为 insert 方法实际上是 INSERT OR IGNORE,结果是 插入行的 rowid,将为 1 或更大(在大多数正常使用情况下)。

  • rowid 是一种特殊的、通常隐藏的列,经常通过使用专门使用 column_name INTEGER PRIMARY KEYcolumn_name INTEGER PRIMARY KEY AUTOINCREMENT< 定义的列来使用别名 Rowid Tables

因此使用:-

public long addM0(Store_M0_DataClass mStore_M0_DataClass)
{
// Create and/or open the database for writing
SQLiteDatabase db = getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_M0_ID, mStore_M0_DataClass.getM0_ID());
values.put(KEY_M0_IMAGE1, mStore_M0_DataClass.getM0_Image1());
values.put(KEY_M0_IMAGE2, mStore_M0_DataClass.getM0_Image2());
values.put(KEY_M0_ENABLE, mStore_M0_DataClass.getM0_Enable());
return db.insert(TABLE_M0, null, values);
}

但是,如果您想存储多个 Store_M0_DataClass 对象,那么您可以:-

public int addManyMo(Store_M0_DataClass[] mStore_M0_DataClasses) {
int rv = 0;
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();// <<<<<<<<<< wrap all inserts in a transaction
for (Store_M0_DataClass m0: mStore_M0_DataClasses) {
if(addM0(m0) > 0) {
rv++;
}
}
// Assumes OK if any inserts have worked, not if none have worked
if (rv > 0) {
db.setTransactionSuccessful();
}
db.endTransaction();
return rv; // Retruns the number of rows inserted
}

至于:-

Is it required to read after write or we can just count on a successful transaction ?

成功的事务提交事务中的内容。提交实际上是将数据写入磁盘,因此提交后无需执行任何操作。

  • 使用 WAL(预写日志记录),数据被写入 WAL 文件而不是数据库(以及 shm 文件)。然而,当访问数据库时,如果 WAL 有数据,它会被有效地读取为数据库的一部分。当检查 WAL 时,WAL 数据被写入数据库。

关于android - 关于SQLite 3,是否需要先写后读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com