Home > Article > Backend Development > How to Extract Column Values from a Go SQL Rows Instance into a []string?
Challenge:
Many programming tasks require extracting row data from database tables into a structured format. In Go, the database/sql package provides Rows instances for iterating through table rows. However, the Scan method of Rows expects pointers to target variables with known types, which can be challenging when the number and types of columns are unknown in advance.
Solution:
To read columns from a Rows instance into a []string, you can use the following approach:
Example:
package main import ( "fmt" "io" "database/sql" ) func dumpTable(rows *sql.Rows, out io.Writer) error { colNames, err := rows.Columns() if err != nil { return err } writer := csv.NewWriter(out) writer.Comma = '\t' readCols := make([]interface{}, len(colNames)) writeCols := make([]string, len(colNames)) for i, _ := range writeCols { readCols[i] = &writeCols[i] } for rows.Next() { err := rows.Scan(readCols...) if err != nil { return err } writer.Write(writeCols) } if err = rows.Err(); err != nil { return err } writer.Flush() return nil }
This code allows you to read columns from a Rows instance and convert them into a []string for further processing.
The above is the detailed content of How to Extract Column Values from a Go SQL Rows Instance into a []string?. For more information, please follow other related articles on the PHP Chinese website!