是否可以以只读模式打开锁定的 sqlite 数据库?
我想使用 python-sqlite3 打开 chromium 站点数据(在 ~/.config/chromium/Default 中),但每当 chromium 运行时它就会被锁定,这是可以理解的,因为可能会进行事务。有没有办法以只读模式打开它,确保我在 chromium 使用它时不会破坏数据库的完整性?
I'd like to open the chromium site data (in ~/.config/chromium/Default) with python-sqlite3 but it gets locked whenever chromium is running, which is understandable since transactions may be made. Is there a way to open it in read-only mode, ensuring that I can't corrupt the integrity of the db while chromium is using it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看来我们可以通过以
immutable
模式打开数据库来绕过锁,例如:正如这里所解释的https://www.sqlite.org/c3ref/open.html
如果底层数据库文件发生更改,或者显然没有看到对文件进行的更新,这可能会导致查询错误,但我发现在每个新查询上重新打开连接有助于 那。
为了使用大多数 SQLite 驱动程序实现相同的效果,因为我们无法直接设置
SQLITE_IOCAP_IMMUTABLE
,最好的方法是使用标志
SQLITE_OPEN_READONLY | 打开连接。 SQLITE_OPEN_URI
允许将file:...?immutable=1
URI 作为文件名
传递。It seems we can bypass the lock by opening the database in
immutable
mode, e.g.:As explained here https://www.sqlite.org/c3ref/open.html
This can cause querying errors if the underlying database file changes, or obviously not seeing updates that are made to the file, but I found that re-opening the connection on each new query helps with that.
To achieve the same thing with most SQLite drivers, because we can't directly set
SQLITE_IOCAP_IMMUTABLE
, the best way is to open the connection with the flagSQLITE_OPEN_READONLY | SQLITE_OPEN_URI
to allow passing thefile:...?immutable=1
URI asfilename
.我相信这取决于事务设置的锁。
https://www.sqlite.org/lockingv3.html#shared_lock
https://www.sqlite.org/lang_transaction.html
SQLite独占事务锁定读取和写入即时和延迟事务仍允许读者的地方。
所以这实际上取决于 Chromium 使用的交易。
I believe it depends on the lock set by the transaction.
https://www.sqlite.org/lockingv3.html#shared_lock
https://www.sqlite.org/lang_transaction.html
SQLite exclusive transactions lock both read and write where immediate and deferred transactions will still allow readers.
So it really depends on the transactions used by Chromium.
Chromium 长时间持有数据库锁?哎呀!这确实不是一个好主意。不过,这不是您的错……
您可以尝试仅复制数据库文件(例如,使用系统实用程序
cp
)并使用该快照进行读取; SQLite 将其所有提交状态保存在每个数据库的单个文件中。是的,有机会看到部分事务,但是在 Unix 上绝对不会遇到锁问题,因为 SQLite 绝对不使用强制锁。 (由于 Windows 上的锁定方案不同,这可能在 Windows 上不起作用。)Chromium is holding a database lock for long periods of time? Yuck! That's really not a very good idea at all. Still, not your fault…
You could try just copying the database file (e.g., with the system utility
cp
) and using that snapshot for reading purposes; SQLite keeps all its committed state in a single file per database. Yes, there's a chance of seeing a partial transaction, but you will definitely not have lock problems on Unix as SQLite definitely doesn't use mandatory locks. (This might well not work on Windows due to the different locking scheme there.)