gpt4 book ai didi

postgresql - GoLang PGX PostgreSQL

转载 作者:行者123 更新时间:2023-12-01 22:25:31 28 4
gpt4 key购买 nike

我希望从lib/pg切换到pgx,但无法在pgx中进行简单的选择。想知道是否有人可以指出此代码出了什么问题。为什么它不起作用?

lib/pg没问题,但pgx一定是缺少的东西。我从pgx示例代码中修改了测试代码以测试我的选择。

我已经发布了我修改的代码以及代码运行时的错误。我看不到如何有无效的内存地址,因为选择返回了。也许有人可以指出这段代码是怎么回事。

package main

import (
"context"
"fmt"
"os"

"github.com/jackc/pgx"
)

var conn *pgx.Conn
var err error

func main() {
conn, err = pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))

if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connection to database: %v\n", err)
os.Exit(1)
}
listTasks()
defer conn.Close(context.Background())
}

func listTasks() error {
rows, _ := conn.Query(context.Background(), "select * from signal")

for rows.Next() {
var s string
var id int32
var v float64
var description string
var description2 string
err := rows.Scan(&s, &id, &v, &description, &description2)
if err != nil {
return err
}
fmt.Printf("%d. %s\n", id, description)
}

return rows.Err()
}

这是我得到的错误
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x4 pc=0x29eb30]

goroutine 1 [running]:
github.com/jackc/pgx.(*Conn).Query(0x0, 0x38deb8, 0x1414090, 0x3238d7, 0x14, 0x0, 0x0, 0x0, 0x14126c0, 0x192e8, ...)
/home/forex/go/src/github.com/jackc/pgx/conn.go:585 +0x18
main.listTasks(0x38deb8, 0x1414090)
/usr/local/forex/test-pgx.go:27 +0x58
main.main()
/usr/local/forex/test-pgx.go:22 +0xbc

最佳答案

您正在以下重新定义conn:

conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))

因此,您无需分配全局 conn

更改为:
var err error
conn, err=px.Connect(...)

根据语言规范:

Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new.



不在同一块中定义 conn,因此简短声明是定义 connerr,而不是分配给 conn

关于postgresql - GoLang PGX PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60179427/

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