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