如题..我想把sql.Rows转成map..请问怎么实现写了下..失败了代码如下
func (this *Admin) Query(query string, args ...interface{}) ([]map[string]interface{}, error) {
db, err := this.getDB()
defer db.Close()
if err != nil {
return nil, err
}
stmt, err := db.Prepare(query)
defer stmt.Close()
if err != nil {
return nil, err
}
res, err := stmt.Query(args...)
defer res.Close()
if err != nil {
return nil, err
}
fields, _ := res.Columns()
fieldslen := len(fields)
ms := []map[string]interface{}{}
for res.Next() {
m := map[string]interface{}{}
scaninterfaces := make([]interface{}, 0, fieldslen)
for _, field := range fields {
//m[field] = 0
scaninterfaces = append(scaninterfaces, m[field])
}
res.Scan(scaninterfaces...)
ms = append(ms, m)
}
return ms, nil
}
更多评论
m := map[string]interface{}{}
scaninterfaces := make([]interface{}, 0, fieldslen)
for _, field := range fields {
//m[field] = 0
scaninterfaces = append(scaninterfaces, m[field])
}
这里m[field]根本没值啊。
另外,Scan必须传递某一字段的指针。
#2