Home > other >  Reading Database Rows into map[string]string
Reading Database Rows into map[string]string

Time:01-27

I would like to read results from a simple SQL table like the following

customer key
A 12345
B 6789

Now, I'd like to structure a map[string]string which has key value pairs equal to the row values like such:

map[A:12345, B:6789]

However, I am having trouble just taking the values out of the query result and dynamically creating the key-val pairs. I'll provide a rough outline of the code (the SQL connection stuff is not an issue, I have that figured out)

import "database/sql"

func main() {

    // Some code to connect to MSSQL...

    db, _ := sql.Open("mssql", connString)

    stmt := "SELECT customer, key from tbl"
    rows, _ := db.Query(stmt)
    defer rows.Close()

    data := make(map[string]string)
    for rows.Next() {
        // Need help here grabbing each row pair and adding them to my map...
    }
}

I'm open to trying to do this with an Empty struct as well, where the fields become the first column of my result set (dynamic) and the value becomes the 2nd column of my result set.

CodePudding user response:

You could temporarily store the values in two variables and then store them in the map:

func main() {
    stmt := "SELECT customer, key from tbl"
    rows, _ := db.Query(stmt)
    defer rows.Close()

    data := make(map[string]string)
    var (
        consumer string
        key string
    )
    for rows.Next() {
        if err := rows.Scan(&consumer, &key); err != nil {
            // Handle err
        }

        data[consumer] = key 
    }

    for k, v := range data {
        fmt.Println(k, v)
    }
    // "A" "12345"
    // "B" "6789"

}

Note that the consumer and key variables are allocated outside of the loop so we can re-use them. Even if the values are empty strings, the variables will be overwritten on each iteration.

  • Related