Home > Backend Development > Golang > How Can I Efficiently Convert Database Rows into a Slice of Maps in Go?

How Can I Efficiently Convert Database Rows into a Slice of Maps in Go?

Linda Hamilton
Release: 2024-12-07 06:23:15
Original
783 people have browsed it

How Can I Efficiently Convert Database Rows into a Slice of Maps in Go?

Creating a Map from Database Rows in Go

When working with database queries, it becomes necessary to retrieve the results and convert them into a convenient data structure. In Go, the standard database/sql package provides the Rows type to represent a set of rows returned from a query. However, the challenge arises when one wants to create a map from these rows, where the map keys are the column names and the values are the corresponding row values.

To address this issue, utilizing the sqlx package is recommended. Here's an example demonstrating how to convert rows to a slice of maps using sqlx:

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)

type Place struct {
    ID      int
    Telcode int
}

func main() {
    db, err := sqlx.Open("mysql", "user:password@tcp(localhost:3306)/database")
    if err != nil {
        fmt.Printf(err)
        return
    }

    rows, err := db.Query("SELECT * FROM place ORDER BY telcode ASC")
    if err != nil {
        fmt.Printf(err)
        return
    }

    places := []map[string]interface{}{}
    for rows.Next() {
        rowMap := make(map[string]interface{})

        if err := rows.MapScan(rowMap); err != nil {
            fmt.Printf(err)
            return
        }

        places = append(places, rowMap)
    }

    fmt.Println(places)
}
Copy after login

In this example, the sqlx.MapScan function is used to scan each row into a map. The resulting slice of maps is stored in the places variable and printed. This approach allows for a more flexible representation of the row data, where the column names become the map keys and the corresponding values are accessible via the map interface.

The above is the detailed content of How Can I Efficiently Convert Database Rows into a Slice of Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template