Home > Backend Development > Golang > How Can I Create a Map from Database Rows in Golang?

How Can I Create a Map from Database Rows in Golang?

DDD
Release: 2024-12-11 12:14:14
Original
391 people have browsed it

How Can I Create a Map from Database Rows in Golang?

Create a Map in Golang from Database Rows

Database/sql provides the Rows.Scan function to retrieve data from a database query. By default, this function expects a specific number of parameters, matching the requested number of columns and potentially their types as well. However, in some cases, it may be desirable to convert the resulting rows into a more flexible data structure, such as a []map[string]interface{}'.

Using sqlx

The sqlx library offers a convenient way to achieve this conversion. By simply replacing []Place{} with []map[string]interface{} in the following code, you can easily generate a list of maps representing the query results:

places := []map[string]interface{}{}
err := db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC")
if err != nil {
    fmt.Printf(err)
    return
}
Copy after login

This solution provides a more generic and flexible approach to handling query results.

The above is the detailed content of How Can I Create a Map from Database Rows in Golang?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template