从数据库Rows在Golang中创建一个地图 [英] Create a Map in Golang from database Rows

查看:238
本文介绍了从数据库Rows在Golang中创建一个地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上做一个查询后,我想得到的行并产生一个 [] map [string] interface {} ,但我不知道如何这样做与API,因为 Rows.Scan()函数需要一个特定数量的参数匹配所需的列数(以及可能的类型),以正确获取数据。

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.

再次,我想推广这个调用,并接受任何查询,并把它变成一个 [] map [string] interface { } ,其中映射包含映射到该行的值的列名。

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.

这可能是非常低效的,结构,因此 interface {} 是单个数据点的结构。

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

只是数据库/ sql包,或者如果需要数据库/ sql /驱动程序包?

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

推荐答案

https://github.com/jmoiron/sqlx =nofollow> sqlx ,它比标准数据库/ sql库更容易做到这一点:

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
}

$ b b

你可以用 [] map [string] interface {} [] Place {} c $ c>,但在可能的情况下,最好使用一个struct,如果你知道你的数据库的结构。您不需要像在接口{} 上进行任何类型的断言。

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{}.

这篇关于从数据库Rows在Golang中创建一个地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆