How to Read SELECT * Columns into a []string in Go?

Barbara Streisand
Release: 2024-11-10 20:30:03
Original
284 people have browsed it

How to Read SELECT * Columns into a []string in Go?

Complexities of Reading SELECT * Columns into []string in Go

A common task in data processing is to retrieve rows from a database table and store them in a convenient format. In Go, you can use the database/sql package to interface with databases. However, encountering a variable number of columns with unknown types can present a challenge.

The sql.Rows type provides access to the results of a query, but its Scan method expects typed fields to populate. Converting the values into a slice of strings ([]string) directly is not straightforward.

Solution: Utilizing an Interface Slice

To address this issue, you must create an interface slice ([]interface{}) that points to each string in your string slice. This involves allocating a temporary slice and setting each element to point to the corresponding element in the string slice.

Example Code:

rawResult := make([][]byte, len(cols))
result := make([]string, len(cols))

dest := make([]interface{}, len(cols)) // A temporary interface{} slice
for i, _ := range rawResult {
    dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
}
Copy after login

Once the interface slice is prepared, you can use it to scan the rows.

Scanning Rows and Converting to Strings

for rows.Next() {
    err = rows.Scan(dest...)
    if err != nil {
        fmt.Println("Failed to scan row", err)
        return
    }

    for i, raw := range rawResult {
        if raw == nil {
            result[i] = "\N"
        } else {
            result[i] = string(raw)
        }
    }

    fmt.Printf("%#v\n", result)
}
Copy after login

This approach allows you to directly read the column values into a string slice, accommodating the variable number and types of columns.

The above is the detailed content of How to Read SELECT * Columns into a []string in Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template