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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With