All the examples that I saw for using sql.Row , return access values โโfrom queries using the position : sql.Rows.scan() require the correct typed variable, it is correctly positioned in the scan() arguments corresponding to the corresponding column to retrieve each returned column value For example, in the following example:
GoDocs based example (with a little mod):
rows, err := db.Query("SELECT name,age FROM users WHERE age>=50") if err != nil { log.Fatal(err) } for rows.Next() { var name string var age int if err := rows.Scan(&name,&age); err != nil { log.Fatal(err) } fmt.Printf("%s is %d\n", name, age) } if err := rows.Err(); err != nil { log.Fatal(err) }
&name and &age must be set correctly (columns 0 and 1) for the rows. Scan () to get the right values โโwith the right types.
Over the years of development for production systems, I tried to avoid this practice because it was not reliable: changing the database in the column layout will easily break your code if it is based on column positions.
It is much more reliable to use column names to get values โโ- this isolates you from changes to the database that add or remove columns that messed up your code based on position. For example, in Delphi and C # all data sets, including columns that return values โโfrom queries, support FieldByName('age').asInteger or fields['age'].value, etc.
Any way to achieve this in Go? If not, this is a big flaw in supporting the Go database and a major disappointment - itโs not at all safe, as already mentioned.
Edit:
Also (maybe this is a new question). The examples I saw seem to require that you get all the columns returned by the query, or the column positions will be distorted.
Suppose there is a utility request in a locked database that I cannot modify or add, and it retrieves several columns, but I only need one of them for my current task. Based on the current sql.Rows.scan() model, I should get all the values โโfrom the query in the application code, even if I don't need them, whereas if I could query for "columnByName" , which would be optional, I could just enter the data I need into your application code. Any work for this?