사용예
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/
'Web > GoLang' 카테고리의 다른 글
go echo request param 획득 방법 (0) | 2021.08.06 |
---|---|
go언어 문자열 slice를 string 으로 합치기 join 함수 (0) | 2021.07.28 |
Golang 구조체 설명 (1) | 2021.07.28 |
[go/golang] SP 프로시저 list 와 ouput parameter 동시에 사용하기 (0) | 2021.07.28 |
[Go/Golang] 구조체 JSON 변환 시, omitempty가 적용되지 않는 경우 (0) | 2021.07.28 |
댓글