Skip to content
Advertisement

Golang: cannot use sql.NamedArg in prepared statement

I have a query that is using NamedArgs from the sql.DB and I’m getting an error when building

cannot use args (type []sql.NamedArg) as type []interface {} in argument to stmt.Exec

The example in the SQL library shows it being used:

Example usage:
    db.ExecContext(ctx, `
     delete from Invoice
     where
     TimeCreated < @end
     and TimeCreated >= @start;`,
     sql.Named("start", startTime),
     sql.Named("end", endTime),
    )

The only difference is that I’m currently using a prepared statement stmt and calling the Exec method on that. I’ve created a slice of NamedArg with my values and it’s using the ... expander.

res, err := stmt.Exec(args...)

What exactly is wrong when the example shows the sql.Named() method call directly in the code? Why wouldn’t an expanded slice work?

Advertisement

Answer

That’s just how passing arguments to a variadic function works in Go. You either pass the individual values which can be of any type, or you pass in a slice whose element type matches exactly that of the variadic parameter and follow it with ....

I.e. you can either do:

res, err := stmt.Exec(
    sql.Named("start", startTime),
    sql.Named("end", endTime),
)

or you can do:

args := []interface{}{
    sql.Named("start", startTime),
    sql.Named("end", endTime),
}
res, err := stmt.Exec(args...)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement