Question with database/sql

1,232 views
Skip to first unread message

Daniel Theophanes

unread,
Feb 20, 2012, 1:20:13 AM2/20/12
to golan...@googlegroups.com
I'm at tip.
I'm trying to get N columns from an arbitrary database query.  A recent change made it possible to use interfaces, but I'm still not getting how to use it.  If I do:

rows.Next() 
cols, _ = rows.Columns()
out := make([]interface{}, len(cols))
err = rows.Scan(&out[0], &out[1])

It works great!  But I had to specify in code the number of args.

If I do:

rows.Next() 
cols, _ = rows.Columns()
out := make([]interface{}, len(cols))
dest := make([]*interface{}, len(cols))
for i, _ := range dest {
   dest[i] = &out[i]
}
err = rows.Scan(dest)

I get the error: expected 2 destination arguments in Scan, not 1

If I do:

rows.Next() 
cols, _ = rows.Columns()
out := make([]interface{}, len(cols))
dest := make([]*interface{}, len(cols))
for i, _ := range dest {
   dest[i] = &out[i]
}
err = rows.Scan(dest ...)

I get the error: cannot use dest (type []*interface {}) as type []interface {} in function argument

Before I try to "fix the code", I wonder if this is supported or if I'm missing something.
Thanks!

Brad Fitzpatrick

unread,
Feb 20, 2012, 1:23:27 AM2/20/12
to Daniel Theophanes, golan...@googlegroups.com
You're close.  Just make dest also be make([]interface{}, len(cols)) and it should work.

Let me know if it doesn't.


Erno Hopearuoho

unread,
Feb 20, 2012, 5:54:45 AM2/20/12
to golang-nuts
What I do myself is:

cols, _ = rows.Columns()
pointers := make([]interface{}, len(cols))
container := make([]sql.NullString, len(cols))
for i, _ := range dest {
pointers[i] = &container[i]
}

err = rows.Scan(pointers...)

You'll have a []interface{} which always points to the same index on
[]sql.NullString, and then you feed rows.Scan the pointers to your
container slice.
(sql.NullString is a struct that holds the data in one variable and
tells you if the data was null in another one)
Reply all
Reply to author
Forward
0 new messages