Home >Backend Development >Golang >How to Dynamically Call Variadic Rows.Scan() Using Reflection in Go?
Calling Variadic Functions with Reflection for SQL Scan
When utilizing the Rows.Scan() function for SQL database querying, it becomes necessary to use reflection to account for the variable number of pointers it accepts. This allows for dynamically populating slices with data from a query result.
Steps to Dynamically Scan Using Reflection
To call a variadic function like Rows.Scan() using reflection, follow these steps:
Code Example
The following code snippet demonstrates how to dynamically scan using reflection:
package main import ( "fmt" _ "github.com/lib/pq" "database/sql" ) func main() { db, _ := sql.Open("postgres", "connection_string") rows, _ := db.Query("SELECT * FROM my_table") columns, _ := rows.Columns() count := len(columns) values := make([]interface{}, count) valuePtrs := make([]interface{}, count) for rows.Next() { for i := range columns { valuePtrs[i] = &values[i] } rows.Scan(valuePtrs...) for i, col := range columns { val := values[i] b, ok := val.([]byte) var v interface{} if ok { v = string(b) } else { v = val } fmt.Println(col, v) } } }
By implementing this method, you can dynamically populate slices with query results without specifying the data types in advance.
The above is the detailed content of How to Dynamically Call Variadic Rows.Scan() Using Reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!