golang 查询数据库并返回json

2021/8/19 19:06:46

本文主要是介绍golang 查询数据库并返回json,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

func getJSON(vehicleType string, sqlString string) (string, error) {
    rows, err := mysql.GetDB(vehicleType).Query(sqlString)
    if err != nil {
        return "", err
    }
    defer rows.Close()

    columns, err := rows.Columns()
    if err != nil {
        return "", err
    }
    count := len(columns)
    tableData := make([]map[string]interface{}, 0)
    values := make([]interface{}, count)
    valuePtrs := make([]interface{}, count)
    for rows.Next() {
        for i := 0; i < count; i++ {
            valuePtrs[i] = &values[i]
        }
        rows.Scan(valuePtrs...)
        entry := make(map[string]interface{})
        for i, col := range columns {
            var v interface{}
            val := values[i]
            b, ok := val.([]byte)
            if ok {
                v = string(b)
            } else {
                v = val
            }
            entry[col] = v
        }
        tableData = append(tableData, entry)
    }
    jsonData, err := json.Marshal(tableData)
    if err != nil {
        return "", err
    }
    //fmt.Println(string(jsonData))
    return string(jsonData), nil
}

 

调用:

start := (i - 1) * pageSize;
        sql := "select id,wnumber from vehicle_steeldust_active where longitude='' OR latitude='' OR active_country='' OR active_province='' OR active_city='' OR active_district='' limit " + strconv.Itoa(start) + "," + strconv.Itoa(pageSize)
        fmt.Println("sql:", sql)
        list, _ := getJSON(vehicleType, string(sql))
        fmt.Println(list)

 



这篇关于golang 查询数据库并返回json的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程