duanjumie8753 2018-08-07 16:24
浏览 21
已采纳

如何在不知道列的情况下从表读取行到地图

In my golang app i need to do SQL query to MySQL to get single row and put result in a map[string]string keys are column names.

But i don't know what will be columns. Query is like

SELECT * FROM mytable

I use "database/sql" .

I found only Scan function

db.QueryRow("SELECT * FROM mytable").Scan(&var1, &var2,...)

but this doesn't work for my condition. I don't know how many variables will be there. And also I need column names.

Is it possible to do with database/sql ?

Update. I found how to solve part of this problem. How to get column names from a result set.

rows, err := db.Query(sqlcommand)

cols, err := rows.Columns()

So, i can use to make keys for a map. But i still don't know how to get values. Because, values can have different type.

data = make(map[string]string)

if rows.Next() {
    columns := make([]interface{}, len(cols))
    columnPointers := make([]interface{}, len(cols))
    for i, _ := range columns {
        columnPointers[i] = &columns[i]
    }

    err = rows.Scan(columnPointers...)

    for i, colName := range cols {
        // value is in columns[i] of interface type.
        // How to extract it from here? 
        // ....
        data[colName] = val
    }
}

P.S. This question is not duplicate of "Get table column names in mysql? ". I wanted to get columns of returned data set, not just a table.

  • 写回答

1条回答 默认 最新

  • duanpiao6679 2018-08-13 11:21
    关注

    You seem to be on the right track. According to the definition of Rows.Scan, you can supply values of the desired destination type, which would be string here. So changing the type of columns to []string should work:

    var db sql.DB
    var sqlcommand string
    
    rows, _ := db.Query(sqlcommand)
    cols, _ := rows.Columns()
    
    data := make(map[string]string)
    
    if rows.Next() {
        columns := make([]string, len(cols))
        columnPointers := make([]interface{}, len(cols))
        for i, _ := range columns {
            columnPointers[i] = &columns[i]
        }
    
        rows.Scan(columnPointers...)
    
        for i, colName := range cols {
            data[colName] = columns[i]
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错