go - Reading database rows into map and appending to a slice of maps -
i trying use maps , slice of maps store rows returned database query. in every iteration of rows.next() , in final slice of 1 same row query. seems problem related memory place being same store cols
, yet not resolve until now.
what thing missing here:
the source code 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 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 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)) := 0; < len(colnames); i++ { colptrs[i] = &cols[i] } rows.next() { err = rows.scan(colptrs...) if err != nil { log.fatal(err) } fmt.println("cols: ", cols) i, col := range cols { mymap[colnames[i]] = col } myslice = append(myslice, mymap) // map 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) }
this because storing in slice pointer map rather copy of map.
from go maps in action:
map types reference types, pointers or slices...
since create map outside loop updates it, keep overwriting data in map new data , appending pointer same map slice each time. multiple copies of same thing in slice (being last record read table).
to handle, move var mymap = make(map[string]interface{})
for rows.next()
loop new map create on each iteration , appended slice.
Comments
Post a Comment