Reputation: 31
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})
Upvotes: 3
Views: 152
Reputation: 34071
@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.
Upvotes: 2