Golang读取Rows到map[string]interface{}中

文章目录

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
}

你可能感兴趣的:(go)