I got an error when I use sqlx transaction,tx.NamedQuery() to run a transaction with postgresql. Sometimes I need the first sql's returning id to execute the other sql, so I used tx.NamedQuery not tx.NamedExec(). The code works correctly if I use tx.NamedExec().
Here is the code, thank you
`
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()
}
`
output:
<nil>
pq: unexpected Parse response 'D'
driver: bad connection
driver: bad connection
driver: bad connection
Process finished with exit code 0