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)