Getting values from a query
A SQL query returns *sql.Rows
, or if you use the QueryRow
methods, it returns *sql.Row
. The next thing you have to do is iterate over the rows and scan the values into Go variables.
How to do it...
Running Query
or QueryContext
implies you are expecting zero or more rows from the query. Because of that, it returns *sql.Rows
.
For the code snippets in this section, we use the following User
struct:
type User struct { ID uint64 Name string LastLogin time.Time AvatarURL string }
This is used with the following table definition:
CREATE TABLE users ( user_id int not null, user_name varchar(32) not null, last_login timestamp null, avatar_url varchar(128) null )
Iterate through the rows and work with each individual result row. In the following example, the query returns...