gpt4 book ai didi

postgresql - 如何正确扫描 pq 数组?

转载 作者:IT王子 更新时间:2023-10-29 00:57:17 27 4
gpt4 key购买 nike

在 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} |

在 Go 中,我对该表进行查询,然后尝试使用 Scan 方法。不幸的是我得到一个错误:

Trace: runtime error: invalid memory address or nil pointer dereference

我的代码:

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

我该如何解决这个问题?

此外,如果我将类型从 pq.Int64Array 更改为 *pq.Int64Array,Go 编译器会给出错误:Cannot range over data *pq.Int64Array 上面的代码。

最佳答案

nil 指针取消引用在 entry 上。通过将 entry 从指针更改为值来修复:

for rows.Next() {
var entry Entry // <--- change on this line
... remaining code as in question
}

关于postgresql - 如何正确扫描 pq 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247355/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com