Web/GoLang

Go SQL error “converting NULL to string is unsupported”

벨포트조던 2021. 7. 28.
반응형

사용예 

MSSQL 에서 null 값이 들어오는 곳에 필요함

솔직히 이해가 안가는데, select로 null 이 들어오면 nil로 컨버팅 되서 문제 없을 거라 생각되는데,

에러가 발생 ... 

sql.NullString, sql.NullInt64  이렇게 변경해서 받고, 다시 info.Int64 이렇게 변환해서 사용

 

더 편한방법이 있으면 수정예정

 

go는 정말 다른언어랑 너무 다른듯 싶음

 

 

Go is a strongly typed programming language, and many SQL databases can also support unknown values. These values can lead to complications in Go when it encounters unexpected results such as NULL (unknown) for an empty string.

// LookupName returns the username from database ID.
func LookupName(id int) (name string, err error) {
    db := Connect()
    defer db.Close()
    err = db.QueryRow("SELECT username FROM accounts WHERE id=?", id).Scan(&name)
    if err != nil {
        return "", fmt.Errorf("lookup name by id %q: %w", id, err)
    }
    return name, nil
}

sql: Scan error on column index 0, name "username": converting NULL to string is unsupported

Instead of saving SQL query values to basic Go types, columns that support NULL or other unknown values should always store their results to the sql package Null types. These include NullBool, NullInt64, NullFloat64, NullTime, NullString and a couple of others.

// LookupName returns the username from database ID.
func LookupName(id int) (name string, err error) {
    db := Connect()
    defer db.Close()
    var usr sql.NullString
    err = db.QueryRow("SELECT username FROM accounts WHERE id=?", id).Scan(&usr)
    if err != nil {
        return "", fmt.Errorf("lookup name by id %q: %w", id, err)
    }
    return usr.String, nil
}

 

 

https://devtidbits.com/2020/08/03/go-sql-error-converting-null-to-string-is-unsupported/

 

반응형

댓글