Scan error on column index 5 ...cannot convert null to int

750 Views Asked by At

In my data there is no null value, thus I can't explain the Scan error...

import (
    "fmt"
    "github.com/jmoiron/sqlx"
    _ "github.com/lib/pq"
    "log"
)
...
func dispatch[T chkRecord](db *sqlx.DB, table []T, query) error {
    err := db.Select(&table, query)
    if err != nil {
        return err  //Scan error on column index 5...converting NULL to int is unsupported
    }
....

Why is that ? A bit of clarification about the context. The &table is not a regular db table,with possible NULLABLE fields, but a view and the Scan error ... fires on a calculated field.

1

There are 1 best solutions below

2
Shubham Dixit On

The problem is, in database you have NULL value for a particular column but sqlx doesn't know how to assign it to your struct one solution is to use pointer types in your table struct .Considering Name is the field in your db which has NULL values

type table struct{
 ID uint 
 Name *string // make this a pointer to the string 

}

If the field Name in your struct is a pointer type, like *string, then sqlx will handle NULL values from the database by setting the pointer to nil.