-2

我正在为我的 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 version go1.12.7 linux/amd64

有人能帮忙吗?

4

1 回答 1

-1

感谢@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在任何功能中使用。

于 2019-08-17T09:16:25.590 回答