How to Convert Database Rows into a Map in Go Using database/sql
When working with databases, it's often necessary to retrieve data and convert it into a format that can be easily manipulated in your Go applications. One common approach is to convert the result rows into a slice of maps. However, the database/sql Rows.Scan function requires a specific number of parameters to match the columns returned by the query.
Creating a Map from Rows Using sqlx
While the database/sql package doesn't provide direct support for converting rows into a slice of maps, you can utilize the sqlx package to simplify the process:
import "github.com/jmoiron/sqlx" db := sqlx.Open("postgres", "user=postgres password=mypassword host=localhost port=5432 dbname=mydb") places := []Place{} err := db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC") if err != nil { fmt.Printf(err) return }
In this example, we're using sqlx to query the place table and store the results in a slice of Place structs. You could replace []Place{} with []map[string]interface{} to create a slice of maps instead.
Note: It's recommended to use structs whenever possible, as they provide type safety and eliminate the need for type assertions, which can be error-prone. However, if you don't know the structure of your database or need to work with dynamic data, you can use a slice of maps for flexibility.
The above is the detailed content of How to Efficiently Convert Database Rows to Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!