Home >Backend Development >Golang >How to Read 'SELECT *' Columns into a []string in Go with Unknown Table Schema?

How to Read 'SELECT *' Columns into a []string in Go with Unknown Table Schema?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 12:01:021019browse

How to Read

How to Read "SELECT *" Columns into a []String in Go

In Go, fetching rows from a database can be achieved with the help of the sql package, while manipulating these rows and writing them into files such as CSV can be done using the csv package. However, one issue arises when the schema of the table is unknown and needs to be determined dynamically.

The Issue: Unknown Table Schema

The Scan method in the Rows type expects fields to be of specific types based on the schema of the table. Without prior knowledge of this schema, it is difficult to determine how many columns exist and what their types are. This poses a challenge when trying to read the columns into a generic type such as []string.

Solution: Using an Interface Type

To overcome this issue, an []interface{} slice can be used to point to each string in the []string slice. This is necessary because Scan expects an array of pointers to the destination variables. The following code snippet demonstrates this approach:

package main

import (
    "database/sql"
    "fmt"
    "log"
)

func main() {
    // Establish a connection to the database.
    db, err := sql.Open("mysql", "user:pass@tcp(localhost:3306)/test")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Execute the "SELECT *" query.
    rows, err := db.Query("SELECT * FROM my_table")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    // Get the column names.
    cols, err := rows.Columns()
    if err != nil {
        log.Fatal(err)
    }

    // Create an interface{} slice pointing to each string in the []string slice.
    var readCols = make([]interface{}, len(cols))
    var writeCols = make([]string, len(cols))
    for i, _ := range writeCols {
        readCols[i] = &writeCols[i]
    }

    // Iterate over the rows and scan the columns into the string slice.
    for rows.Next() {
        if err := rows.Scan(readCols...); err != nil {
            log.Fatal(err)
        }
        fmt.Println(writeCols)
    }
}

In this example, the readCols slice contains pointers to each element in the writeCols slice. When Scan is called, the values from the row are assigned to the variables pointed to by readCols, which are subsequently copied into the writeCols slice. This allows for the dynamic reading of columns from the database into a string slice.

The above is the detailed content of How to Read 'SELECT *' Columns into a []string in Go with Unknown Table Schema?. 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