Exec / sql: converting argument $1 type: unsupported type []interface {}, a slice of interface
Closed this issue · 4 comments
ghollf commented
How can Exec be called with varying arguments?
args := make([]any, len(values)+1)
args[0] = y + 1
for i, v := range values {
args[i+1] = v
}
// args = append(args, values)
fmt.Print(args)
_, err := stmt.Exec(args)
This ends with error "sql: converting argument $1 type: unsupported type []interface {}, a slice of interface"?
rittneje commented
Please provide a full reproducer.
ghollf commented
Derived from "simple" example...
package main
import (
"database/sql"
"os"
_ "github.com/mattn/go-sqlite3"
)
func main() {
os.Remove("./foo.db")
db, err := sql.Open("sqlite3", "./foo.db")
if err != nil {
panic(err)
}
defer db.Close()
sqlStmt := "create table foo (id integer not null primary key, name text)"
_, err = db.Exec(sqlStmt)
if err != nil {
panic(err)
}
stmt, err := db.Prepare("insert into foo(id, name) values(?, ?)") // will be dynamic sql stmt with varying values
if err != nil {
panic(err)
}
defer stmt.Close()
args := []any{1, "xyz"} // number of args will be dynamic too
_, err = stmt.Exec(args)
if err != nil {
panic(err)
}
}
mattn commented
Please use ...
_, err = stmt.Exec(args...)
ghollf commented
damn simple... I'll have to read the language specs again