当我使用sqlx事务,tx.NamedQuery()与postgresql运行事务时出错。 有时我需要第一个sql的返回id来执行另一个sql,所以我使用了tx.NamedQuery而不是tx.NamedExec()。如果我使用tx.NamedExec()。
,代码可以正常工作这是代码,谢谢
`
package main
import (
"log"
_ "github.com/lib/pq" // PostgreSQL
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
"fmt"
)
type Test struct {
Id int `json:"id" db:"id" form:"id"`
Name string `json:"name" db:"name" form:"name"`
Role pq.Int64Array `json:"role" db:"role" form:"role"`
}
func main() {
db, err := sqlx.Connect("postgres", "user=postgres password=*** dbname=*** sslmode=disable")
if err != nil {
log.Panicln(err)
}
defer db.Close()
db.SetMaxOpenConns(1)
tx, err := db.Beginx()
test := Test{Name: "name", Role: []int64{1, 2, 3}}
_, err1 := tx.NamedQuery(`INSERT INTO test(name,role) VALUES (:name,:role)returning id`, test)
fmt.Println(err1)
_, err1 = tx.NamedQuery(`INSERT INTO test(name,role) VALUES (:name,:role)returning id`, test)
fmt.Println(err1)
_, err1 = tx.NamedQuery(`INSERT INTO test(name,role) VALUES (:name,:role)returning id`, test)
fmt.Println(err1)
_, err1 = tx.NamedQuery(`INSERT INTO test(name,role) VALUES (:name,:role)returning id`, test)
fmt.Println(err1)
_, err1 = tx.NamedQuery(`INSERT INTO test(name,role) VALUES (:name,:role)returning id`, test)
fmt.Println(err1)
tx.Commit()
}
`
输出:
<nil>
pq: unexpected Parse response 'D'
driver: bad connection
driver: bad connection
driver: bad connection
Process finished with exit code 0