duanmeng3476 2015-06-01 08:36
浏览 42
已采纳

将数据库行读入地图并追加到地图切片

I am trying to use maps and slice of those maps to store rows returned from a database query. But what I get in every iteration of the rows.Next() and in final is the slice of the one same row from the query. It seems the problem is related to the memory place being same I store the cols, yet I could not resolve it until now.

What is the thing am I missing here:

The source code is as follows:

package main

import (
    "database/sql"
    _ "github.com/lib/pq"

    "fmt"
    "log"

    "reflect"
)
var myMap = make(map[string]interface{})
var mySlice = make([]map[string]interface{}, 0)

func main(){
    fmt.Println("this is my go playground.")

    // DB Connection-
    db, err := sql.Open("postgres", "user=postgres dbname=proj2-dbcruddb-dev password=12345 sslmode=disable")
    if err != nil {
        log.Fatalln(err)
    }
    rows, err := db.Query("SELECT id, username, password FROM userstable")
    defer rows.Close()
    if err != nil {
        log.Fatal(err)
    }

    colNames, err := rows.Columns()
    if err != nil {
        log.Fatal(err)
    }
    cols := make([]interface{}, len(colNames))
    colPtrs := make([]interface{}, len(colNames))
    for i := 0; i < len(colNames); i++ {
        colPtrs[i] = &cols[i]
    }

    for rows.Next() {
        err = rows.Scan(colPtrs...)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("cols: ", cols)

        for i, col := range cols {
            myMap[colNames[i]] = col
        }
        mySlice = append(mySlice, myMap)

        // Do something with the map
        for key, val := range myMap {
            fmt.Println("Key:", key, "Value:", val, "Value Type:", reflect.TypeOf(val))
        }
        fmt.Println("myMap: ", myMap)
        fmt.Println("mySlice: ", mySlice)

    }
    fmt.Println(mySlice)
}
  • 写回答

1条回答 默认 最新

  • doufan9377 2015-06-01 09:05
    关注

    This is because what you are storing in the slice is a pointer to a map rather than a copy of the map.

    From Go maps in action:

    Map types are reference types, like pointers or slices...

    Since you create the map outside the loop that updates it, you keep overwriting the data in the map with new data and are appending a pointer to the same map to the slice each time. Thus you get multiple copies of the same thing in your slice (being the last record read from your table).

    To handle, move var myMap = make(map[string]interface{}) into the for rows.Next() loop so a new map is create on each iteration and then appended to the slice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?