When I use scan I have to write all the variables into the scan beforehand. i need a solution where i can use data using things like sprintf
Is there a way I can access the data without defining a variable?
func (dbs *item) ReadQuery() {
var (
unit_name, unit_position_name string
)
rows, err := db.Query(dbs.query)
for rows.Next() {
rows.Scan(&unit_name, &unit_position_name)
if err != nil {
log.Fatal(err)
}
}
}
for example;
row["unit_name"]
or
unit_name,unit_position string
val:= fmt.Sprintf("%s , %s",unit_name,unit_position_name)
row[val]
CodePudding user response:
Here's how to scan a row without explicitly declaring a variable for value in the row.
Make a slice for the values. Make a slice with the address of those values. Scan to the addresses.
func example(db *sql.DB, query string) {
rows, err := db.Query(query)
if err != nil {
log.Fatal(err)
}
cols, err := rows.Columns()
if err != nil {
log.Fatal(err)
}
addrs := make([]any, len(cols))
for rows.Next() {
values := make([]any, len(cols))
for i := range addrs {
addrs[i] = &values[i]
}
rows.Scan(addrs...)
if err != nil {
log.Fatal(err)
}
// The variable values contains the row values.
// Here's an example of how to use the values.
// Replace the for loop with your code to
// process the row.
for i := range cols {
fmt.Printf("%s: %v\n", cols[i], values[i])
}
}
}