当我们用sql查出数据时,第一个问题当然是如何将rows转成map集合了 ,不多说直接上代码
func DoQuery(db *sql.DB, sqlInfo string, args ...interface{}) ([]map[string]interface{}, error) {
rows, err := db.Query(sqlInfo, args...)
if err != nil {
return nil, err
}
columns, _ := rows.Columns()
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 {
item[columns[i]] = *data.(*interface{}) //取实际类型
}
list = append(list, item)
}
_ = rows.Close()
return list, nil
}
如何将map、list转成对应的结构体见我的另一篇博客:https://blog.csdn.net/weimingjue/article/details/94601017