英文:
Precautions to avoid SQLite file/database locks when concurrent goroutines try to access the database?
问题
我目前正在开发一个应用程序,其中多个goroutine可能会同时尝试查询或更新一个SQLite数据库文件(使用github.com/mattn/go-sqlite3和database/sql驱动程序)。
我不确定的是锁定/并发访问是如何控制的;驱动程序是否会处理它,还是我需要找到一种方法来使用互斥锁或通道来序列化请求?
有人知道如果数据库文件由于某种原因被锁定,驱动程序是否会等待执行操作并重试,还是会抛出错误并放弃?
英文:
I'm currently working on an application where multiple goroutines may at some point try to query or update a SQLite database file concurrently (using github.com/mattn/go-sqlite3 and database/sql drivers.)
What I'm not sure of is how locking/concurrent access is controlled; does the driver take care of it, or do I need to find a way to serialize requests with a mutex or channel?
Does someone know if the driver will wait to perform operations and retry if the database file is locked for some reason, or would it throw an error and give up?
答案1
得分: 3
你应该为每个goroutine打开一个单独的连接。驱动程序会负责锁定和访问,但是你应该为每个goroutine使用不同的连接。
此外,你可以在连接打开时添加一些参数来加快某些访问速度:
gDb, err = sql.Open("sqlite3", "file:databaselocked.sqlite?cache=shared&mode=rwc")
请参考Github上这个线程的评论,特别是该软件包作者的链接评论:https://github.com/mattn/go-sqlite3/issues/148#issuecomment-56764080
英文:
You should open a separate connection per goroutine. The driver will take care of locking and access, but you should have a different connection per goroutine.
Also, you can add some parameters to your connection opening to speed up some access:
gDb, err = sql.Open("sqlite3", "file:databaselocked.sqlite?cache=shared&mode=rwc")
See the comments on this thread in Github, especially the linked comment by the author of the package: https://github.com/mattn/go-sqlite3/issues/148#issuecomment-56764080
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论