在Golang中,使用EXCEPT的SQL查询不起作用。

huangapple go评论80阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2022年8月3日 18:56:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73220532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定