Precautions to avoid SQLite file/database locks when concurrent goroutines try to access the database?

huangapple go评论81阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年4月5日 23:59:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/36431452.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定