使用 2 个进程处理数据库
我有一个有两个部分的应用程序。
- 创建内容的服务。
- 使用内容的应用程序
其中每个都作为不同的进程运行。问题是他们两个共享一个数据库。当服务尝试写入内容且 UI 正在读取数据时,我经常遇到数据库锁定错误。反之亦然。 这件事该怎么办呢?
- 用于访问数据库的类是单例类。但由于 UI 和该服务是2个不同的进程,我认为有2个单例。所以这没有帮助。
- 我想即使是同步也无济于事,因为这又是因为两个不同的进程。
Content Providers
也许是一个选项,但由于我使用复杂的查询来挖掘信息,因此也很难使用它。
如何让两个进程共享数据库。 任何提示将不胜感激。
I have a an application that has 2 parts.
- A service which creates content.
- An application that uses the content
Each of these run as different processes. The problem is that both of them share a database. And I frequently get database locked error, both when the service tries to write something and the UI is reading data. Also vice versa.
How do go about this?
- The class used to access DB is a singleton class. But since both UI & the service are 2 different processes, there are 2 singletons I presume. So that doesn't help.
- Even
synchronise
won't help I suppose, since again because of 2 different processes. Content Providers
maybe an option, but since I use complex queries to dig info, it would be really hard to use that too.
How do I get the two processes share the database.
Any cues would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用内容提供商是一种选择。另一个方法是查看 Berkeley DB。 BDB SQL API与 SQLite 兼容,并且 BDB 锁管理器允许多个线程和/或进程同时读/写数据库。
Using a content provider is one option. Another is to take a look at Berkeley DB. The BDB SQL API is SQLite compatible and the BDB lock manager allows multiple threads and/or processes to read/write to the database concurrently.
后关闭连接
每次操作捕获数据库锁定错误
,并在 50 毫秒后尝试重新连接,或者让服务处理数据库,并且活动向服务询问数据
可能存在 isDatabaseInUseMethod 吗?
close the connection after each operation
catch the database locked error and try to reconnect after 50ms
or let the service handle the database and the activity ask the service for data
may be there is isDatabaseInUseMethod ?
您应该使用内容提供程序通过一个来源集中您的数据库查询。在内容提供程序内部,您可以使用任何您想要的锁定机制,以确保您没有并发访问。您还可以考虑使用内容观察器来协调服务操作和数据库更改。
You should use a content provider to funnel your database queries through one source. Inside of the content provider you can use any locking mechanisms you would like to ensure you're not having concurrent access. You may also think about using content observers to coordinate service actions with changes to the database.
以下是一篇关于如何在 Android 上使用 SQLite 进行锁定以及需要注意的事项的精彩文章: http://kagii.squarespace.com/journal/2010/9/10/android-sqlite-locking.html
我想你会在那里找到一些答案:)
The following is a great article on how locking works with SQLite on Android and what things to be aware of: http://kagii.squarespace.com/journal/2010/9/10/android-sqlite-locking.html
I would think you'll find some answers there :)