Should errors like the following appear when scanning NULL values from a TEXT field into a string?:
Scan error on column index 2: unsupported Scan, storing driver.Value type <nil> into type *string
Seems to me that just using the zero value of string would be appropriate for nil/NULL.
The original query and scan were:
row := db.QueryRow("SELECT id, name, thumbUrl FROM x WHERE y=? LIMIT 1", model.ID)
err := row.Scan(&an_int64, &a_string, &another_string))
I don't quite see how I could avoid this error without too much trouble.
https://github.com/golang/go/wiki/SQLInterface explains how to deal with nulls. In short, you need to use a nullable variable type to store a nullable value. So in your case, you'd use
var an_int64 sql.NullInt64
var a_string sql.NullString
var another_string sql.NullString
row := db.QueryRow("SELECT id, name, thumbUrl FROM x WHERE y=? LIMIT 1", model.ID)
err := row.Scan(&an_int64, &a_string, &another_string))
I think the Scan function should return sql.ErrNoRows in this case, at least according to the QueryRow documentation.
I have not tested this with other drivers, so I don't know where the problem is.
id := 123
var username string
err := db.QueryRow("SELECT username FROM users WHERE id=?", id).Scan(&username)
switch {
case err == sql.ErrNoRows:
log.Printf("No user with that ID.")
case err != nil:
log.Fatal(err)
default:
fmt.Printf("Username is %s\n", username)
}
@toreolsensan what result do you get?
Sorry, my mistake. I was including an aggregate function in the query, so when there was no matching rows I got nulls back. The QueryRow().Scan() statement does work when I either get one row with data or no row at all.
Closed because is answered
Most helpful comment
https://github.com/golang/go/wiki/SQLInterface explains how to deal with nulls. In short, you need to use a nullable variable type to store a nullable value. So in your case, you'd use