database/sql: Creating a []map[string]interface{} from sql.Rows?

2,743 views
Skip to first unread message

Craig Weber

unread,
Nov 30, 2015, 10:10:06 AM11/30/15
to golang-nuts
Hello,

I need to build a []map[string]interface{} from sql.Rows, but I can't figure out how to do it. I came across this question on StackOverflow (http://stackoverflow.com/questions/17840963/create-a-map-in-golang-from-database-rows), but none of the answers are satisfactory (it's also a dated question). I wanted to check to see if anyone on this list had any better solutions, preferably using the standard library if it's not overly complex.

Thanks,
Craig

Kyle Wolfe

unread,
Nov 30, 2015, 10:37:51 AM11/30/15
to golang-nuts
Craig,

If you know what the table structure is ahead, it's trivial to do a normal scan and then return a map[string]interface{} form your scan. Beccause of this, I'm assuming that you have a situation where you're unaware of the table structure at runtime and your doing a "select *" all the time? If this is the case, databse/sql is not set up for this use case from what I see in the do, as driver.Value is not exported (https://golang.org/src/database/sql/sql.go#L1615). With that said, I agree with the first response in that SO. Use sqlx (https://godoc.org/github.com/jmoiron/sqlx#Row.MapScan)

C Banning

unread,
Nov 30, 2015, 12:33:12 PM11/30/15
to golang-nuts
Get a Rows value, 'r', with the db.Query().  r.Columns has the map keys in sequence - 'cols'; r.Next() will get you a row; and r.Scan() will walk through the values for the map keys in sequence of cols[i].

Daniel Theophanes

unread,
Nov 30, 2015, 3:28:52 PM11/30/15
to golang-nuts

dja...@gmail.com

unread,
Nov 30, 2015, 11:15:59 PM11/30/15
to golang-nuts
see this file:

it is usable as independent package.

Djadala
Reply all
Reply to author
Forward
0 new messages