gpt4 book ai didi

android - 在 sqlite (Android) 中锁定数据库或表

转载 作者:行者123 更新时间:2023-11-29 14:25:35 25 4
gpt4 key购买 nike

那是我的问题:

我有一个包含列的表:ID、VALUE 和 SYNCHRONICED。最后一个是一个标志,指示自上次更新以来是否已将行发送到服务器。我有一些正在运行的线程可以访问数据库

我的问题出现在那个用例中(有 2 个线程 T1 和 T2:

T1-->Start_Send-->Query_Values-->Send_to_server-->wait_answer-->sync=1_for_sent_rows
T2------------------------->Update_a_row_sent

此时 T1 已经用 sync=1 标记了 T2 更新的值。

有什么办法可以避免这个问题吗?

  • 查询和更新的方法不同,所以不能在方法上使用synchronized。
  • 如果 T2 一直阻塞到 T1 结束就没有问题

谢谢

最佳答案

既然你问过如何在 android 上锁定数据库/表,你可以使用 SQLiteDatabase.beginTransaction() 来实现:

来自安卓文档http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html :

public void beginTransaction ()

Since: API Level 1

Begins a transaction in EXCLUSIVE mode.

来自 sqlite 3 http://www.sqlite.org/lang_transaction.html

After a BEGIN EXCLUSIVE, no other database connection except for read_uncommitted connections will be able to read the database and no other connection without exception will be able to write the database until the transaction is complete.

beginTransaction 启动一个事务并将您的数据库置于独占锁中,因此当 T1 select 运行时它会阻止 T2 更新行,直到 T1 调用 db.endTransaction() 。

public yourMethod() {
db.beginTransaction();

//do whatever you want with db;

db.setTransactionSuccessful();
db.endTransaction();
}

关于android - 在 sqlite (Android) 中锁定数据库或表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6934563/

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