Possible to bind arrays, for use in e.g. IN (?)
queries?
#103
-
I'd like to do something like this and pass a list of strings to var callsInFile = []string{"N7YHF", "W0NY"}
err = sqlitex.Execute(conn,
`SELECT id, callsign FROM callsigns WHERE callsign IN (?)`,
&sqlitex.ExecOptions{Args: []any{callsInFile},
ResultFunc: func(stmt *sqlite.Stmt) error {
fmt.Printf("%d\n", stmt.ColumnInt64(0))
return nil
}})
if err != nil {
panic(err)
} It doesn't work at the moment; am I missing a way to do it or is it simply not possible? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I unblocked myself, I can construct my own parameter list that matches the length of the array I pass in as var callsInDatabase = map[string]int64{}
var parameters []string
for _ = range callsInFile {
parameters = append(parameters, "?")
}
var parameterString = strings.Join(parameters, ", ")
parameterValues := make([]interface{}, len(callsInFile))
for i, v := range callsInFile {
parameterValues[i] = v
}
err = sqlitex.Execute(conn,
fmt.Sprintf(`SELECT id, callsign FROM callsigns WHERE callsign IN (%s)`, parameterString),
&sqlitex.ExecOptions{Args: parameterValues,
ResultFunc: func(stmt *sqlite.Stmt) error {
callsInDatabase[stmt.ColumnText(1)] = stmt.ColumnInt64(0)
return nil
}})
if err != nil {
panic(err)
} I do think it would be nice to have the option to bind those arrays directly for |
Beta Was this translation helpful? Give feedback.
-
SQLite does not have a direct way of passing arrays into statements. As you've discovered, you can create a statement every time, but that ends up eating some performance because you have to compile a new statement every time. Another approach is to use the SELECT id, callsign FROM callsigns WHERE callsign IN (SELECT value FROM json_each(?)); And then pass in a JSON-encoded array as the single parameter. |
Beta Was this translation helpful? Give feedback.
SQLite does not have a direct way of passing arrays into statements. As you've discovered, you can create a statement every time, but that ends up eating some performance because you have to compile a new statement every time. Another approach is to use the
json_each
function:And then pass in a JSON-encoded array as the single parameter.