dongqiu9018 2016-01-02 18:21
浏览 84
已采纳

GO:从SQL查询返回映射

I am querying a mysql database in a GO function and want to return key value pairs in a map but can't quite figure out how to accomplish this. So far I have this function:

func GetData(callIds []string) map[string]Records {
    //db insert
    db, err := sql.Open("mysql", mySql)
    if err != nil {
        fmt.Printf(err.Error())
    }
    defer db.Close()
    //db query
    var foo string
    err = db.QueryRow("select foo from bardata where callId = %v", 1).Scan(&foo)
    if err != nil {
        fmt.Printf(err.Error())
    }
    fmt.Println(foo)

    return nil

I want to return a map with the key being callId and value being foo for each row returned from the query.

  • 写回答

2条回答 默认 最新

  • dongwuwan5646 2016-01-02 18:44
    关注

    First, you need to build up your query. As it is, you're not even using your function input. Since we have a variable number of arguments, we need to do a little work to construct the right number of placeholders:

    query := `select callid, foo from bardata where callid in (` +
        strings.Repeat(`?,`, len(callIds) - 1) + `?)`
    

    then, execute with the values passed in:

    rows, err := db.Query(query, callIds...)
    if err != nil {
        // handle it
    }
    defer rows.Close()
    

    then collect the results:

    ret := map[string]string{}
    for rows.Next() {
        var callid, foo string
        err = rows.Scan(&callid, &foo)
        if err != nil {
            // handle it
        }
        ret[callid] = foo
    }
    
    return ret
    

    Caveats:

    1. This will cause a placeholder mismatch error if callIds is an empty slice. If that's possible, then you need to detect it and handle it separately (maybe by returning an error or an empty map — querying the DB shouldn't be necessary).

    2. This returns a map[string]string where the values are whatever "foo" is. In your question you have the function returning a map[string]Records but there's no information about what a Records might be or how to fetch one.

    3. You might want to handle sql.ErrNoRows differently from other errors.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算