Go-sqlite3: unsupported Scan, storing driver.Value type <nil> into type *string

Created on 3 Mar 2017  路  5Comments  路  Source: mattn/go-sqlite3

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.

question

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

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))

All 5 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jacentsao picture jacentsao  路  6Comments

eaglebush picture eaglebush  路  7Comments

tiaguinho picture tiaguinho  路  3Comments

hackertron picture hackertron  路  10Comments

KrisCarr picture KrisCarr  路  11Comments