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

时间:2014-08-15 10:45:17

标签: go

我需要同时执行多个SQL个查询(selectupdatedelete),如果出现任何goroutine错误,则回滚。因此问题是:DB transactions对于并发访问是否安全?

2 个答案:

答案 0 :(得分:9)

从多个goroutines访问

DB是安全的:

  

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

     

多个goroutine可以安全地同时使用。

同样Stmt可以安全地从多个goroutines中使用:

  

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

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

  

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

答案 1 :(得分: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)

取决于接受的行为,您可以使用不同的隔离级别:

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

一般而言,"更高"你使用的隔离级别,你得到的并发性越差。在使用更多锁定并阻止来自其他事务的并发查询的意义上更差。如果您知道您将更新所选的行,则可以选择...进行更新。

请参阅示例http://en.wikipedia.org/wiki/Isolation_%28database_systems%29以获得更详尽的解释。