How to map db.QueryRow.Scan results into map in Go language?
Apr 02, 2025 am 11:21 AM Go language database operation: cleverly map db.QueryRow.Scan
results to map
In Go database operations, it is common to map query results to custom structures. However, sometimes it is necessary to map the results into map
. This article will explain in detail how to scan the results of db.QueryRow.Scan
into map[string]interface{}
and resolve common errors.
It is wrong to use map[string]interface{}
directly as Scan
parameter, because Scan
function requires a pointer to write data. The following code snippet shows common errors:
res := map[string]interface{}{"id": nil, "name": nil, "password": nil, "add_time": nil} // ... Scan(res["id"], res["name"], ...) // Error!
res["id"]
, etc. return a value of type interface{}
, not a pointer. Scan
function cannot write data to these values.
The correct way to do this is to allocate memory space for each map
value and use pointers:
res := map[string]interface{}{"id": new(int), "name": new(string), "password": new(string), "add_time": new(int64)}
Here, use the new()
function to allocate memory for int
, string
and int64
types respectively, and get their pointers. Scan
function can write data to the memory address pointed to by these pointers.
The improved selectOne
function is as follows:
func selectOne(id int) { res := map[string]interface{}{"id": new(int), "name": new(string), "password": new(string), "add_time": new(int64)} fmt.Println("Initial map:", res) // Add print statements to facilitate debugging of sql := "select id, name, password, add_time from test where id = ?" err := db.QueryRow(sql, id).Scan(res["id"], res["name"], res["password"], res["add_time"]) if err != nil { fmt.Println("Failed to get data:", err.Error()) } else { fmt.Println("Result map:", res) // Add print statements to facilitate debugging // Access data in map idVal := *res["id"].(*int) nameVal := *res["name"].(*string) // ... } }
Note that accessing data in map
requires type assertions, such as *res["id"].(*int)
. This ensures that interface{}
is converted to int
type correctly. We have also added print statements to facilitate debugging and understanding data flow. The SQL statement has also been adjusted to specify the column names to be queried to avoid potential column name mismatch problems. Remember that the key name of map
must be consistent with the database column name.
With this approach, the results of db.QueryRow.Scan
can be mapped to map
effectively and avoid common pointer errors. Remember to always allocate memory for the values ??in map
and use pointers.
The above is the detailed content of How to map db.QueryRow.Scan results into map in Go language?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

MySQL is an open source relational database management system, mainly used to store, organize and retrieve data. Its main application scenarios include: 1. Web applications, such as blog systems, CMS and e-commerce platforms; 2. Data analysis and report generation; 3. Enterprise-level applications, such as CRM and ERP systems; 4. Embedded systems and Internet of Things devices.

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

Avoiding SQL injection in PHP can be done by: 1. Use parameterized queries (PreparedStatements), as shown in the PDO example. 2. Use ORM libraries, such as Doctrine or Eloquent, to automatically handle SQL injection. 3. Verify and filter user input to prevent other attack types.

Renaming a database in MySQL requires indirect methods. The steps are as follows: 1. Create a new database; 2. Use mysqldump to export the old database; 3. Import the data into the new database; 4. Delete the old database.

Java middleware is a software that connects operating systems and application software, providing general services to help developers focus on business logic. Typical applications include: 1. Web server (such as Tomcat and Jetty), which handles HTTP requests; 2. Message queue (such as Kafka and RabbitMQ), which handles asynchronous communication; 3. Transaction management (such as SpringTransaction), which ensures data consistency; 4. ORM framework (such as Hibernate and MyBatis), which simplifies database operations.

There are three ways to verify the correctness of SQL files: 1. Use DBMS's own tools, such as mysql command line tools; 2. Use special SQL syntax checking tools, such as SQLLint; 3. Use IDEs such as IntelliJIDEA or VisualStudioCode; 4. Write automated scripts for checking.

Lock waiting issues can be solved by optimizing SQL statements, using appropriate transaction isolation levels, and monitoring database performance. 1. Optimize SQL statements to reduce lock holding time, such as improving query efficiency through indexing and partitioning. 2. Choose the appropriate transaction isolation level to avoid unnecessary lock waiting. 3. Monitor database performance and promptly discover and deal with lock waiting problems.
