Skip to content

Instantly share code, notes, and snippets.

@msnoigrs
Created January 22, 2019 01:01
Show Gist options
  • Save msnoigrs/e625e6f250c44a2cdc67d3a95f240826 to your computer and use it in GitHub Desktop.
Save msnoigrs/e625e6f250c44a2cdc67d3a95f240826 to your computer and use it in GitHub Desktop.
# https://stackoverflow.com/questions/29102725/go-sql-driver-get-interface-column-values
var myMap = make(map[string]interface{})
rows, err := db.Query("SELECT * FROM myTable")
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)
}
for i, col := range cols {
myMap[colNames[i]] = col
}
// Do something with the map
for key, val := range myMap {
fmt.Println("Key:", key, "Value Type:", reflect.TypeOf(val))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment