英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论