Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Map in Golang from database Rows

Basically after doing a query I'd like to take the resulting rows and produce a []map[string]interface{}, but I do not see how to do this with the API since the Rows.Scan() function needs a specific number of parameters matching the requested number of columns (and possibly the types as well) to correctly obtain the data.

Again, I'd like to generalize this call and take any query and turn it into a []map[string]interface{}, where the map contains column names mapped to the values for that row.

This is likely very inefficient, and I plan on changing the structure later so that interface{} is a struct for a single data point.

How would I do this using just the database/sql package, or if necessary the database/sql/driver package?

like image 401
lucidquiet Avatar asked Jul 24 '13 17:07

lucidquiet


2 Answers

Look at using sqlx, which can do this a little more easily than the standard database/sql library:

places := []Place{}
err := db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC")
if err != nil {
    fmt.Printf(err)
    return
}

You could obviously replace []Place{} with a []map[string]interface{}, but where possible it is better to use a struct if you know the structure of your database. You won't need to undertake any type assertions as you might on an interface{}.

like image 60
elithrar Avatar answered Nov 20 '22 00:11

elithrar


I haven't used it (yet), but I believe the "common" way to do what you are asking (more or less) is to use gorp.

like image 4
Ask Bjørn Hansen Avatar answered Nov 19 '22 23:11

Ask Bjørn Hansen