美文网首页
golang查询数据返回json

golang查询数据返回json

作者: EasyNetCN | 来源:发表于2020-08-12 14:56 被阅读0次

    在使用xorm中,有直接的方法返回map[string]string,返回map[string]interface{}时,返回的不是实际数据类型,下面的代码用于数据同步,可以返回实际的数据类型

    func GetQueryColumns(rows *sql.Rows) ([]string, map[string]string, error) {
        columnTypes, err := rows.ColumnTypes()
    
        if err != nil {
            return nil, nil, err
        }
    
        length := len(columnTypes)
    
        columns := make([]string, length)
        columnTypeMap := make(map[string]string, length)
    
        for i, ct := range columnTypes {
            columns[i] = ct.Name()
            columnTypeMap[ct.Name()] = ct.DatabaseTypeName()
        }
    
        return columns, columnTypeMap, nil
    }
    func QueryForInterface(db *sql.DB, sqlInfo string, args ...interface{}) ([]map[string]interface{}, error) {
        rows, err := db.Query(sqlInfo, args...)
    
        defer rows.Close()
    
        if err != nil {
            return nil, err
        }
    
        columns, columnTypeMap, err := GetQueryColumns(rows)
    
        if err != nil {
            return nil, err
        }
    
        columnLength := len(columns)
        cache := make([]interface{}, columnLength) 
    
        for index, _ := range cache { 
            var a interface{}
            cache[index] = &a
        }
    
        var list []map[string]interface{} //返回的切片
    
        for rows.Next() {
            _ = rows.Scan(cache...)
    
            item := make(map[string]interface{})
    
            for i, data := range cache {
                if ct, ok := columnTypeMap[columns[i]]; ok {
                    if (ct == "VARCHAR" || ct == "DATETIME") && *data.(*interface{}) != nil {
                        item[columns[i]] = string((*data.(*interface{})).([]byte))
                    } else {
                        item[columns[i]] = *data.(*interface{})
                    }
                } else {
                    item[columns[i]] = *data.(*interface{}) 
                }
    
            }
    
            list = append(list, item)
        }
    
        return list, nil
    }
    

    相关文章

      网友评论

          本文标题:golang查询数据返回json

          本文链接:https://www.haomeiwen.com/subject/ojzpdktx.html