本文介绍了适用于Android SQLite的数据库队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android应用程序,其中包含一个相当大的数据库,可以从多个线程访问该数据库.我开始获取数据库锁定的异常.我的问题是,有没有一种创建数据库队列的方法(类似于iOS中的FMDataBase.Queue)?

I have an Android Application that holds a fairly large Database which is accessed from multiple threads. I am starting to get Database locked Exceptions. My question, is there a way of creating a database Queue (similar to FMDataBase.Queue in iOS)?

我已经做过一些研究,但我不想创建一个帮助器类,因为我的许多数据库查询和插入内容都不相同,因此为每个查询创建一个方法是不可行的.

I have done some research and I don't want to create a helper class as a lot of my database queries and inserts are different so creating a method for each query is not feasible.

我可以放

if(!db.isLocked)
{
    //exec(BLAH)
}
 else
{
  //try{thread.sleep(1000);}... then some retry code
}

在每个数据库功能上,但必须有一个比这更好的方法.

on every database function but there must be a better way than this.

此外,如果线程锁定后的睡眠时间为1000ms,它将仍然崩溃,并且如果数据库锁定了10ms,我将等待990ms来运行查询,这对于用户体验来说不是很好.

moreover if the thread is locked after is has slept for 1000ms, it will still crash and if the db is locked for 10ms I will be waiting for 990ms for the query to run, which is not great for user experience.

是否可以创建一个队列,以便一旦数据库被解锁,发送给数据库的任何命令都将被执行?

Is is possible to create a Queue so that any commands sent to the db will be executed once the the db becomes unlocked?

任何建议将不胜感激

推荐答案

将所有数据库写入文件移动到IntentService,托管LinkedBlockingQueue的常规服务,由单例SQLiteOpenHelper持有的LinkedBlockingQueue等.

Move all your database writes to an IntentService, a regular service hosting a LinkedBlockingQueue, a LinkedBlockingQueue held by your singleton SQLiteOpenHelper, etc.

用一种方法包装数据库I/O的开销并不特别多,少于您在问题中提出的建议.

The overhead to wrap a database I/O in a method not especially much, less than what you were proposing doing in your question.

调整数据库访问权限(例如EXPLAIN关键字,然后设置适当的索引).使用Traceview来确定问题所在的确切位置.如果您的问题出在数据库事务中(例如,您打开自己的事务并在其中进行大量工作),请考虑使用yieldIfContendedSafely() .

Tune your database access (e.g., EXPLAIN keyword, then set up appropriate indices). Use Traceview to determine exactly where your problems lie. If your problems are in a database transaction (e.g., you open your own transaction and do a ton of work inside of it), consider using yieldIfContendedSafely().

这篇关于适用于Android SQLite的数据库队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 12:23