Nur*_*bek 3 postgresql go go-gorm
在PostgreSQL数据库中,我有一个表:
| ORGANIZATION_ID | FACTOR_IDS | CALCULATION_VALUES |
|-----------------|--------------|---------------------|
| 1 | {1,2,3,4,5} | {0,66.66,50,100,80} |
| 2 | NULL | NULL |
| 1 | {6,7,8,9,10} | {0,77.77,60,110,90} |
Run Code Online (Sandbox Code Playgroud)
在Go中,我查询该表,然后尝试使用该Scan方法。不幸的是我得到一个错误:
Trace: runtime error: invalid memory address or nil pointer dereference
Run Code Online (Sandbox Code Playgroud)
我的代码:
type Entry struct {
OrganizationID int
FactorIDS pq.Int64Array
CalculationValues pq.Float64Array
}
rows, err = database.DBGORM.Raw(`SELECT * FROM ANALYTICS`, ID).Rows()
if err != nil {
utils.Logger().Println(err)
return
}
defer rows.Close()
for rows.Next() {
var entry *Entry
if err = rows.Scan(&entry.OrganizationID, &entry.FactorIDS, &entry.CalculationValues); err != nil {
utils.Logger().Println(err) // <- RAISE ERROR
return
}
if entry.FactorIDS != nil {
for index, value := range factorID {
// some code here
}
}
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
另外,如果我将类型从pq.Int64Array更改*pq.Int64Array为Go编译器,则会出现错误:Cannot range over data *pq.Int64Array对于上面的代码。
nil指针取消引用为on entry。通过entry从指针更改为值来解决:
for rows.Next() {
var entry Entry // <--- change on this line
... remaining code as in question
}
Run Code Online (Sandbox Code Playgroud)