英文:
Golang postgres Commit unknown command error?
问题
使用postgres 9.3
和go 1.6
。
我一直在尝试使用go
的pq
库进行事务处理。
// 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("UPDATE t_name SET a = $1", 1)
//Read out rows
rows.Close() //<- 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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论