I'm building mysql query dynamically ( due the mysql IN
clause) so I need to pass a list of arguments as the sql.Query function requires. Any idea how can do that ? I don't really understand how the variadic type works or how I can 'generate' it. If I pass a slice the sql complains that there is only one parameter instead of len(in clause params)
thus I can only assume that the function sees the slice as a parameter instead a list ( variadic ) of parameters.
My query / code
var carsa []string
q := `SELECT field1,field2 FROM cooltable WHERE nicecars IN(?` + strings.Repeat(",?", len(ha.cars)-1) + ")"
hs := strings.Join(carsa, "','")
hs = "'" + hs + "'"
rows, err := cx.Query(q, country, hs)
sql Query
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
Edit: The actual code I'm trying to run fails with error sql: converting Exec argument #0's type: unsupported type []interface {}, a slice
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
argsS := []string{"apple", "greph", "3rd"}
db, err := sql.Open("mysql", dbUser+":"+dbPass+"@tcp("+dbHost+":3306)/"+dbName)
if err != nil {
return
}
query := `SELECT id,label FROM fruits WHERE country=? AND stack IN(?` + strings.Repeat(",?", len(args)-1) + ")"
args := make([]interface{}, len(ha))
args["country"] = interface{}("France")
for i, v := range query {
args[i] = interface{}(v)
}
rows, err := db.Query(q, args...)
if err != nil {
return
}
var id, label string
for rows.Next() {
if err = rows.Scan(&id, label); err != nil {
fmt.Printf("%v", err)
}
}
}