Go SQL驱动程序get interface {}列值 [英] Go SQL driver get interface{} column values

查看:105
本文介绍了Go SQL驱动程序get interface {}列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用go sql驱动程序从数据库表中读取数据,并将值转换为[]map[string]interface{}.列名是映射的键,值是interface{}.我将所有列添加到数组中.我正在 https://github.com/上使用"RawBytes"的代码示例以go-sql-driver/mysql/wiki/Examples 为例.

I am trying to use go sql driver to read from database tables and I am converting the values to []map[string]interface{}. The column name is the key of the map and the values are of interface{}. I am adding all the columns into an array. I am using the code sample for "RawBytes" at https://github.com/go-sql-driver/mysql/wiki/Examples as an example to start with.

但是,在示例中-所有列值都按如下所示转换为string

However, in the example -all the column values are converted to string as follows,

// Fetch rows
for rows.Next() {
    // get RawBytes from data
    err = rows.Scan(scanArgs...)
    if err != nil {
        panic(err.Error()) // proper error handling instead of panic in your app
    }

    // Now do something with the data.
    // Here we just print each column as a string.
    var value string
    for i, col := range values {
        // Here we can check if the value is nil (NULL value)
        if col == nil {
            value = "NULL"
        } else {
            value = string(col) //ATTN : converted to string here
        }
        fmt.Println(columns[i], ": ", value)
    }
    fmt.Println("-----------------------------------")
}

有没有办法将其保留为interface{},所以我可以在使用[]map[string]interface{}

Is there a way to retain it as interface{} so I can do the necessary type casting while using the columns from []map[string]interface{}

推荐答案

请参见此https://stackoverflow.com/questions/20271123/go-lang-sql-in-parameters 答案是我的答案基于的.使用它,您可以执行以下操作:

See this https://stackoverflow.com/questions/20271123/go-lang-sql-in-parameters answer which my answer is based on. Using that you can do something like this:

var myMap = make(map[string]interface{})
rows, err := db.Query("SELECT * FROM myTable")
defer rows.Close()
if err != nil {
    log.Fatal(err)
}
colNames, err := rows.Columns()
if err != nil {
    log.Fatal(err)
}
cols := make([]interface{}, len(colNames))
colPtrs := make([]interface{}, len(colNames))
for i := 0; i < len(colNames); i++ {
    colPtrs[i] = &cols[i]
}
for rows.Next() {
    err = rows.Scan(colPtrs...)
    if err != nil {
        log.Fatal(err)
    }
    for i, col := range cols {
        myMap[colNames[i]] = col
    }
    // Do something with the map
    for key, val := range myMap {
        fmt.Println("Key:", key, "Value Type:", reflect.TypeOf(val))
    }
}

使用反射包,然后可以根据需要获取每一列的类型,如最后循环所示.

Using the reflect package you can then get the Type for each column as needed as demonstrated with the loop at the end.

这是通用的,可以与任何表,列数等一起使用.

This is generic and will work with any table, number of columns etc.

这篇关于Go SQL驱动程序get interface {}列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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