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)

 

上一篇:python测试开发django-121.bootstrap-table弹出模态框修表格数据提交


下一篇:mycat分库