如何在Go中执行IN查询?

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

How do I do IN queries in Go?

问题

我想在Go中使用“database/sql”包运行像这样的查询:

SELECT id, name FROM users WHERE id IN (1,2,3,4);

如何在查询命令中使用变量替换?例如,我想要做这个(当然不起作用):

db.Query("SELECT id, name FROM users WHERE id IN (?)", []int{1,2,3,4})
英文:

I'd like to run a query like this in Go using "database/sql" package:

SELECT id, name FROM users WHERE id IN (1,2,3,4);

How do I use variable substitution in the query command? E.g., I want to do this (which of course doesn't work):

db.Query("SELECT id, name FROM users WHERE id IN (?)", []int{1,2,3,4})

答案1

得分: 2

@Volker在评论中建议一些数据库驱动程序可以为您扩展切片。但是,任何驱动程序都可以单独处理切片元素:

db.Query("SELECT id, name FROM users WHERE id IN (?, ?, ?, ?)", 1, 2, 3, 4)

当然,您需要在编写时确切地知道切片中将有多少个元素,这可能不是情况。生成正确数量的问号很简单,并且为您提供了一般解决方案:

ints := []interface{}{1,2,3,4}
marks := strings.Repeat("?,", len(ints) - 1) + "?"
db.Query("SELECT id, name FROM users WHERE id IN (" + marks + ")", ints...)

如果您的切片可能为空,您将不得不以某种方式处理它。

英文:

@Volker suggests in the comments that some database drivers may be able to expand the slice for you. Any driver can handle the slice elements individually, however:

db.Query("SELECT id, name FROM users WHERE id IN (?, ?, ?, ?)", 1, 2, 3, 4)

Of course, you'd need to know exactly how many elements are going to be in the slice when you write that, which probably isn't the case. Generating the correct number of question marks is simple enough and gives you a general solution:

ints := []interface{}{1,2,3,4}
marks := strings.Repeat("?,", len(ints) - 1) + "?"
db.Query("SELECT id, name FROM users WHERE id IN (" + marks + ")", ints...)

If your slice might be empty, you'll have to handle that somehow.

huangapple
  • 本文由 发表于 2013年5月19日 02:29:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/16627602.html
匿名

发表评论

匿名网友

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

确定