dongqianchi0512 2016-06-19 12:48
浏览 95
已采纳

迭代MySQL记录并在GoLang中创建JSON

I'm trying to read data from a MySQL database from my Go app.

var queryStr string = "SELECT * FROM Customers"
rows, err := db.Query(queryStr)

defer rows.Close()
for rows.Next() {
    // do stuffs
}

The query it's ok and it works; now I'd like to easily map each record of the MySQL query to a Customer object that I've previuosly defined as showed below:

type Customer struct {
    id              IntegerType     `json:"id"`
    name            string          `json:"name"`
    surname         string          `json:"surname"`
}

How can I do that?

Second question: once I get an array of Customer object how can I easily put it into a new JSON object under a specific key called "data"?

thanks for your support :)

  • 写回答

1条回答 默认 最新

  • dpbdl44228 2016-06-19 14:27
    关注

    Export fields so they can be used on JSON:

    type Customer struct {
       ID      int         `json:"id"`
       Name    string      `json:"name"`
       Surname string      `json:"surname"`
    }
    

    Declare a value to be marshaled to JSON:

    var v struct {
        Data []Customer `json:"data"`
    }
    

    Query for the specific fields:

    var queryStr string = "SELECT id, name, surname FROM Customers"
    rows, err := db.Query(queryStr)
    

    Loop through rows adding to value.

    defer rows.Close()
    for rows.Next() {
        // Scan one customer record
        var c Customer
        if err := rows.Scan(&c.ID, &c.Name, &c.Surnmae); err != nil {
            // handle error
        }
        v.Data = append(v.Data, c)
    }
    if rows.Err() != nil {
        // handle error
    }
    

    Marshal the value to JSON

    p, err := json.Marshal(v)
    if err != nil {
        // handle error
    }
    

    The value p is a []byte containing the JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?