Golang postgres 提交未知命令错误?

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

Golang postgres Commit unknown command error?

问题

使用postgres 9.3go 1.6

我一直在尝试使用gopq库进行事务处理。

// Good
txn, _ := db.Begin()
txn.Query("UPDATE t_name SET a = 1")
err := txn.Commit() // err is nil

// Bad
txn, _ := db.Begin()
txn.Query("UPDATE t_name SET a = $1", 1)
err := txn.Commit() // 给我一个"unexpected command tag Q"的错误
// 尽管数据已经提交

出于某种原因,当我使用带参数的Query语句时,总是会从Commit()得到一个"unexpected command tag Q"的错误。这个错误是什么意思(Q代表什么?)为什么会出现这个错误?

我认为这里是错误产生的地方。

英文:

Using postgres 9.3, go 1.6

I've been trying to use transactions with the go pq library.

// Good
txn, _ := db.Begin()
txn.Query("UPDATE t_name SET a = 1")
err := txn.Commit() // err is nil

// Bad
txn, _ := db.Begin()
txn.Query("UPDATE t_name SET a = $1", 1)
err := txn.Commit() // Gives me a "unexpected command tag Q" error
// although the data is committed

For some reason, when I execute a Query with parameters, I always get an unexpected command tag Q error from the Commit(). What is this error (what is Q?) and why am I getting it?

I believe this is where the error is created.

答案1

得分: 11

首先,我同意评论中的Dmitri的观点,在这种情况下,你应该使用Exec。

然而,在收到相同问题后,我开始进行了调查:

Query 返回2个参数,一个是Rows指针,一个是错误。对于Rows对象,你必须在使用完毕后关闭它:

// 修正后的代码
txn, _ := db.Begin()
rows, _ := txn.Query("UPDATE t_name SET a = $1", 1)
// 读取rows
rows.Close() //<- 这将解决错误
err := txn.Commit()

然而,当使用rows.Close()时,我无法看到与数据库的通信有任何差异,这表明这可能是pq中的一个错误。

英文:

To start of i agree whit Dmitri from the comments, in this case you should probably use Exec.

However after receiving this same issue I started digging:

Query returns 2 arguments a Rows pointer and an error. What you always have to do with a Rows object is to close it when you are don with it:

// Fixed
txn, _ := db.Begin()
rows, _ := txn.Query(&quot;UPDATE t_name SET a = $1&quot;, 1)
//Read out rows
rows.Close() //&lt;- This will solve the error
err := txn.Commit()

I was however unable to see any difference in the traffic to the database when using rows.Close() witch indicates to me that this might be a bug in pq.

huangapple
  • 本文由 发表于 2016年3月30日 05:59:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/36295883.html
匿名

发表评论

匿名网友

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

确定