How to map db.QueryRow.Scan results into map in Go language?
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!

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.