数据库/ sql事务对象对于并发访问是否安全?

hey*_*hey 10 go

我需要执行多个SQL查询(select,update,delete兼)和回滚如果有够程出现了错误.因此问题是:DB 事务是否可以安全地进行并发访问?

One*_*One 11

从多个goroutine访问DB是安全的:

DB是表示零个或多个底层连接池的数据库句柄.

多个goroutine并发使用是安全的.

Stmt可以安全地从多个够程使用:

Stmt是一份准备好的声明.Stmt对于多个goroutine并发使用是安全的.

sql.Tx每个goroutine 应该只使用一个:

调用DB.Begin后,返回的Tx将绑定到单个连接

  • “每个goroutine仅应使用一个sql.Tx”。尽管我仍然看不到您引用的文档中的内容,但您可能只想对每个Tx讲一遍。 (2认同)

Len*_*art 1

一般来说是的,但您必须定义所需的安全级别。交易中可能发生的三种标准现象是:

- Dirty reads (read uncommitted data)
- Nonrepeatable reads (a row is retrieved twice and the values within the row differ between reads)
- Phantom reads ( two identical queries are executed, and the collection of rows returned by the second query is different from the first)
Run Code Online (Sandbox Code Playgroud)

根据接受的行为,您可以使用不同的隔离级别:

- Read uncommitted (all phenomena possible)
- Read committed (dirty read prevented)
- Repeatable reads (phantom read can occur)
- Serializable (non of the phenomena is possible)
Run Code Online (Sandbox Code Playgroud)

一般来说,您使用的隔离级别“越高”,获得的并发性就越差。较差是因为使用了更多的锁并阻止了来自其他事务的并发查询。如果您知道要更新选定的行,则可以选择 ... 进行更新。

例如,请参阅http://en.wikipedia.org/wiki/Isolation_%28database_systems%29以获得更全面的解释。

  • 我怀疑 OP 是在问 [sql.Tx](http://golang.org/pkg/database/sql/#Tx) 是否可以从多个 goroutine 中同时使用。但它不能。 (16认同)