在使用gorm时,出现了golang语法错误,错误信息为”在postgres中的$1附近”。

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

golang syntax error at or near "$1" in postgres using gorm

问题

我正在尝试根据用户名查找多个用户。我使用的是以下的gorm代码:

err := db.Where("username IN ?", []string{"name1", "name2"}).Find(&users).Error

但生成的查询语句是:

SELECT * FROM "users_customer"."user" WHERE (username IN 'name1','name2')

而正确的查询语句应该是:

SELECT * FROM "users_customer"."user" WHERE username IN ('name1','name2')

因此会抛出错误 pq: syntax error at or near "$1"。我使用的语法与文档中所述相同,即 db.Where("name IN ?", []string{"jinzhu", "jinzhu 2"}).Find(&users),但不知道为什么在我的情况下不起作用。

英文:

I am trying to find multiple users based on their name. I am using gorm as follow:

err := db.Where("username IN ?", []string{"name1", "name2"}).Find(&users).Error

But the generated query is:

SELECT * FROM "users_customer"."user" WHERE (username IN 'name1','name2')

when the correct query should be:

SELECT * FROM "users_customer"."user" WHERE username IN ('name1','name2')

So the error pq: syntax error at or near "$1" is thrown. I use the same syntax as stated in the doc, which is db.Where("name IN ?", []string{"jinzhu", "jinzhu 2"}).Find(&users) but don't know why in my case it doesn't work.

答案1

得分: 2

Gorm默认在每一侧添加',并且不添加括号()

你应该手动添加,像这样:

names := []string{"name1", "name2"}

commaSep := "'" + strings.Join(names, "', '") + "'"
err := db.Where("username IN (?)", commaSep).Find(&users).Error

你可以在这里运行它:https://go.dev/play/p/ox3H2gL1yek

或者

err := db.Where("username IN (?)", []string{"name1", "name2"}).Find(&users).Error
英文:

Gorm by default ad ' this at each side and it does not add brackets ().

You should add it manually like this :

    names := []string{"name1", "name2"}

	commaSep := "'" + strings.Join(names, "', '") + "'"
	err := db.Where("username IN (?)", commaSep).Find(&users).Error

You can run it here : https://go.dev/play/p/ox3H2gL1yek

OR

err := db.Where("username IN (?)", []string{"name1", "name2"}).Find(&users).Error

huangapple
  • 本文由 发表于 2021年12月14日 19:09:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/70347895.html
匿名

发表评论

匿名网友

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

确定