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) }
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!