此代码提供AFAIK正确的JSON输出[{},{}],但每行都会附加并替换所有以前的行,因此结果仅显示最后一行的副本。
var rows *sql.Rows
rows, err = db.Query(query)
cols, _ := rows.Columns()
colnames, _ := rows.Columns()
vals := make([]interface{}, len(cols))
for i, _ := range cols {
vals[i] = &cols[i]
}
m := make(map[string]interface{})
for i, val := range vals {
m[colnames[i]] = val
}
list := make([]map[string]interface{}, 0)
for rows.Next() {
err = rows.Scan(vals...)
list = append(list, m)
}
json, _ := json.Marshal(list)
fmt.Fprintf(w,"%s\n", json)
这是在循环遍历行的幕后发生的事情:
循环1:{“ID”:“1”,“NAME”:" John}
循环2:{“ID”:“2”,“NAME”:“Jane Doe”} {“ID”:“2”,“NAME”:“Jane Doe”}
循环3:{“ID”:“3”,“NAME”:“唐老鸭”} {“ID”:“3”,“NAME”:“唐老鸭”} {“ID”:“3” ,“NAME”:“唐老鸭”}
rows.Scan获取正确的值,但它会附加AND替换所有以前的值。
最终输出是
[{“ID”:“3”,“NAME”:“Donald Duck”},{“ID”:“3”,“NAME”:“Donald Duck”},{“ID”:“3” ,“NAME”:“唐老鸭”}]
但应该是这样的:
[{“ID”:“1”,“NAME”:“John Doe”},{“ID”:“2”,“NAME”:“Jane Doe”},{“ID”:“3” ,“NAME”:“唐老鸭”}]
我做错了什么?
你可能会投票,但请解释原因。我仍然是Golang的新手,想要学习。
答案 0 :(得分:2)
我修复了它并用评论解释你做错了什么:
// 1. Query
var rows *sql.Rows
rows, err = db.Query(query)
cols, _ := rows.Columns()
// 2. Iterate
list := make([]map[string]interface{}, 0)
for rows.Next() {
vals := make([]interface{}, len(cols))
for i, _ := range cols {
// Previously you assigned vals[i] a pointer to a column name cols[i].
// This meant that everytime you did rows.Scan(vals),
// rows.Scan would see pointers to cols and modify them
// Since cols are the same for all rows, they shouldn't be modified.
// Here we assign a pointer to an empty string to vals[i],
// so rows.Scan can fill it.
var s string
vals[i] = &s
// This is effectively like saying:
// var string1, string2 string
// rows.Scan(&string1, &string2)
// Except the above only scans two string columns
// and we allow as many string columns as the query returned us — len(cols).
}
err = rows.Scan(vals...)
// Don't forget to check errors.
if err != nil {
log.Fatal(err)
}
// Make a new map before appending it.
// Remember maps aren't copied by value, so if we declared
// the map m outside of the rows.Next() loop, we would be appending
// and modifying the same map for each row, so all rows in list would look the same.
m := make(map[string]interface{})
for i, val := range vals {
m[cols[i]] = val
}
list = append(list, m)
}
// 3. Print.
b, _ := json.MarshalIndent(list, "", "\t")
fmt.Printf("%s\n", b)
不用担心,当我还是初学者时,我很难理解。
现在,有趣的事情:
var list []map[string]interface{}
rows, err := db.Queryx(query)
for rows.Next() {
row := make(map[string]interface{})
err = rows.MapScan(row)
if err != nil {
log.Fatal(err)
}
list = append(list, row)
}
b, _ := json.MarshalIndent(list, "", "\t")
fmt.Printf("%s\n", b)
这与上面的代码相同,但使用sqlx。有点简单,没有?
sqlx是database/sql
之上的扩展程序,其方法是将行直接扫描到地图和结构中,因此您不必手动执行此操作。
我认为你的模型作为结构看起来更好:
type Person struct {
ID int
Name string
}
var people []Person
rows, err := db.Queryx(query)
for rows.Next() {
var p Person
err = rows.StructScan(&p)
if err != nil {
log.Fatal(err)
}
people = append(people, p)
}
你不这么认为吗?