Reputation: 45
I can't understand why my INSERT query doesn't properly work with parameters, but works fine with direct values in it.
Golang, Postgres.
This code works fine:
fmt.Printf("connected to %s\n", ec.DBName)
q := `
INSERT INTO some_table (name, num) VALUES ('sample',20)
EXCEPT
SELECT name, num FROM some_table;`
_, err = db.Query(q)
if err != nil {
fmt.Println(err)
}
But this one raises an error:
fmt.Printf("connected to %s\n", ec.DBName)
q := `
INSERT INTO some_table (name, num) VALUES ($1,$2)
EXCEPT
SELECT name, num FROM some_table;`
_, err = db.Query(q, "sample", 20)
if err != nil {
fmt.Println(err)
}
The error is "pq: EXCEPT types text and integer cannot be matched"
Upvotes: 1
Views: 253
Reputation: 81
You can send both values as string and try to cast them to the desired types via sql. Something like this -
q := `
INSERT INTO some_table (name, num)
VALUES (cast($1 as text), cast($2 as int))
EXCEPT
SELECT name, num FROM some_table;`
_, err = db.Query(q, "sample", "20")
if err != nil {
fmt.Println(err)
}
Upvotes: 1