英文:
Scanning a range type using pgx
问题
我有一个 int4range 类型的列,并希望使用 pgx 进行扫描。我将类型定义为 pgtype.Int4range,但是我看到了以下错误:
无法将 &{{18 2} {86 2} i e 2} 分配给 **int64
我所做的只是:
for rows.Next() {
....
err = rows.Scan(
...
&healthRange)
我是否漏掉了什么?
英文:
I have column of the type int4range and would like to scan it using pgx. I am defining the type as pgtype.Int4range but I am seeing the error
cannot assign &{{18 2} {86 2} i e 2} to **int64
All I am doing is
for rows.Next() {
....
err = rows.Scan(
...
&healthRange)
Is there something I am missing?
答案1
得分: 2
Scan
将当前行的值按位置读入到目标值(dest
)中。很可能是Scan
的参数与行中的列不匹配。
以下是问题的复现代码:
package main
import (
"fmt"
"github.com/jackc/pgx"
"github.com/jackc/pgx/pgtype"
)
func main() {
conn, err := pgx.Connect(pgx.ConnConfig{
Host: "localhost",
Port: 5432,
User: "username",
Password: "password",
})
if err != nil {
panic(err)
}
defer conn.Close()
var (
healthRange pgtype.Int4range
anotherVar *int64
)
row := conn.QueryRow(`select '[18,86)'::int4range, 2`)
err = row.Scan(&anotherVar, &healthRange)
if err != nil {
panic(err)
}
fmt.Printf("%+v", healthRange)
}
错误信息如下:
panic: can't scan into dest[0]: cannot assign &{{18 2} {86 2} i e 2} to **int64
应用以下更改以修复此问题:
- row.Scan(&anotherVar, &healthRange)
+ row.Scan(&healthRange, &anotherVar)
顺便提一下,pgtype.Int4range
位于github.com/jackc/pgx@v3
中,该版本于2017年首次发布。考虑升级到最新版本github.com/jackc/pgx/v5
。
英文:
Scan
reads the values from the current row into dest values positionally. It's most likely that the parameters passed to Scan
does not match the columns in the row.
Here is a reproducer of the issue:
package main
import (
"fmt"
"github.com/jackc/pgx"
"github.com/jackc/pgx/pgtype"
)
func main() {
conn, err := pgx.Connect(pgx.ConnConfig{
Host: "localhost",
Port: 5432,
User: "username",
Password: "password",
})
if err != nil {
panic(err)
}
defer conn.Close()
var (
healthRange pgtype.Int4range
anotherVar *int64
)
row := conn.QueryRow(`select '[18,86)'::int4range, 2`)
err = row.Scan(&anotherVar, &healthRange)
if err != nil {
panic(err)
}
fmt.Printf("%+v", healthRange)
}
The error message is:
panic: can't scan into dest[0]: cannot assign &{{18 2} {86 2} i e 2} to **int64
Apply this change to fix the issue:
- row.Scan(&anotherVar, &healthRange)
+ row.Scan(&healthRange, &anotherVar)
BTW, pgtype.Int4range
is in github.com/jackc/pgx@v3
, which was first published in 2017. Consider upgrading to the latest version, github.com/jackc/pgx/v5
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论