英文:
SQL query with EXCEPT doesn't work in Golang
问题
我无法理解为什么我的INSERT查询在使用参数时无法正常工作,但在其中直接使用值时可以正常工作。
Golang,Postgres。
这段代码可以正常工作:
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)
}
但这段代码会引发错误:
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)
}
错误是"pq: EXCEPT类型的文本和整数无法匹配"。
英文:
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"
答案1
得分: 1
你可以将这两个值都作为字符串发送,并尝试通过 SQL 将它们转换为所需的类型。类似这样的方式 -
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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论