如何正确扫描pq数组?

在 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.Int64ArrayGo 编译器,则会出现错误:Cannot range over data *pq.Int64Array对于上面的代码。


明月笑刀无情
浏览 117回答 2
2回答

catspeake

nil 指针解除引用已开启entry。entry通过将指针更改为值来修复:for rows.Next() {&nbsp; &nbsp; var entry Entry&nbsp; // <--- change on this line&nbsp; &nbsp; ... remaining code as in question}

汪汪一只猫

由于这些 &entry.OrganizationID、&entry.FactorIDS、&entry.CalculationValues,它令人恐慌。由于条目是指针类型,并且您尚未为其初始化内存。如果你想要指针类型的结构,你可以像这样初始化它:for rows.Next() {&nbsp; &nbsp; entry:=new(Entry)&nbsp; &nbsp; if err = rows.Scan(&entry.OrganizationID, &entry.FactorIDS, &entry.CalculationValues); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; utils.Logger().Println(err) // <- RAISE ERROR&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; if entry.FactorIDS != nil {&nbsp; &nbsp; &nbsp; &nbsp; for index, value := range factorID {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // some code here&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go