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
DDDOriginal
2024-12-11 12:14:14432browse

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
}

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!

Statement:
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