gpt4 book ai didi

go - 库/pq : Runtime error when querying a database

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:38 24 4
gpt4 key购买 nike

我正在为我的 Go 后端设置一个 PostgreSQL 数据库,但是我在尝试读取一个表时遇到了这个错误:

runtime error: invalid memory address or nil pointer dereference
/FwzFiles/go/src/runtime/panic.go:82 (0x4423b0)
panicmem: panic(memoryError)
/FwzFiles/go/src/runtime/signal_unix.go:390 (0x4421df)
sigpanic: panicmem()
/FwzFiles/go/src/database/sql/sql.go:1080 (0x4e59d9)
(*DB).conn: db.mu.Lock()
/FwzFiles/go/src/database/sql/sql.go:1379 (0x4e7197)
(*DB).prepare: dc, err := db.conn(ctx, strategy)
/FwzFiles/go/src/database/sql/sql.go:1352 (0x4e6f58)
(*DB).PrepareContext: stmt, err = db.prepare(ctx, query, cachedOrNewConn)
/FwzFiles/go/src/database/sql/sql.go:1369 (0x9c8020)
(*DB).Prepare: return db.PrepareContext(context.Background(), query)
/FwzFiles/go-projects/first-postgresql/main.go:62 (0x9c7fe2)
AllEmployees: queryStmt, err := db.Prepare("SELECT * FROM employees ORDER BY id")
/home/f4ww4z/go/pkg/mod/github.com/gin-gonic/gin@v1.4.0/context.go:124 (0x991109)
(*Context).Next: c.handlers[c.index](c)
/home/f4ww4z/go/pkg/mod/github.com/gin-gonic/gin@v1.4.0/recovery.go:83 (0x9a43d9)
RecoveryWithWriter.func1: c.Next()
/home/f4ww4z/go/pkg/mod/github.com/gin-gonic/gin@v1.4.0/context.go:124 (0x991109)
(*Context).Next: c.handlers[c.index](c)
/home/f4ww4z/go/pkg/mod/github.com/gin-gonic/gin@v1.4.0/logger.go:240 (0x9a3480)
LoggerWithConfig.func1: c.Next()
/home/f4ww4z/go/pkg/mod/github.com/gin-gonic/gin@v1.4.0/context.go:124 (0x991109)
(*Context).Next: c.handlers[c.index](c)
/home/f4ww4z/go/pkg/mod/github.com/gin-gonic/gin@v1.4.0/gin.go:389 (0x99a921)
(*Engine).handleHTTPRequest: c.Next()
/home/f4ww4z/go/pkg/mod/github.com/gin-gonic/gin@v1.4.0/gin.go:351 (0x99a153)
(*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/FwzFiles/go/src/net/http/server.go:2774 (0x6ccd87)
serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/FwzFiles/go/src/net/http/server.go:1878 (0x6c8970)
(*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/FwzFiles/go/src/runtime/asm_amd64.s:1337 (0x459c50)
goexit: BYTE $0x90 // NOP

[GIN] 2019/08/17 - 16:25:18 | 500 | 23.812025ms | ::1 | GET /employees

这是错误指向的地方(main.go:63):

func AllEmployees(c *gin.Context) {
// Query the Postgres employees table
queryStmt, err := db.Prepare("SELECT * FROM employees ORDER BY id")
rows, err := queryStmt.Query() // line 63
if err != nil {
panic(err)
}
defer rows.Close()

// Extract the employees data from the query
result := Employees{}
for rows.Next() {
employee := Employee{}
err := rows.Scan(&employee.ID, &employee.Name, &employee.Salary, &employee.Age)
if err != nil {
panic(err)
}
result.Employees = append(result.Employees, employee)
}

c.JSON(http.StatusOK, gin.H{
"employees": result,
})
}

它应该返回我在 employees 表中手动创建的两行。注意我已成功连接到数据库,只是在查询时出错。

Go版本:go版本go1.12.7 linux/amd64

有人可以帮忙吗?

最佳答案

感谢@Flimzy 的提示。似乎我的全局变量 db 还没有初始化。我将我的数据库初始化代码更改为

func initDb() {
theDb, err := sql.Open("postgres", connection)
if err != nil {
fmt.Println("Cannot connect to database")
panic(err)
}

err = theDb.Ping()
if err != nil {
fmt.Println("Cannot ping the database")
panic(err)
}
db = theDb // Setting the global var

fmt.Println("Connected to Db successfully!")
}

然后我可以在任何函数中使用 db

关于go - 库/pq : Runtime error when querying a database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57534635/

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