jjzjj

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

coder 2024-07-13 原文

我正在为我的 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/

有关go - 库/pq : Runtime error when querying a database的更多相关文章

  1. ruby-on-rails - Textmate 'Go to symbol' 相当于 Vim - 2

    在Railcasts上,我注意到一个非常有趣的功能“转到符号”窗口。它像Command-T一样工作,但显示当前文件中可用的类和方法。如何在vim中获取它? 最佳答案 尝试:helptags有各种程序和脚本可以生成标记文件。此外,标记文件格式非常简单,因此很容易将sed(1)或类似的脚本组合在一起,无论您使用何种语言,它们都可以生成标记文件。轻松获取标记文件(除了下载生成器之外)的关键在于格式化样式而不是实际解析语法。 关于ruby-on-rails-Textmate'Gotosymbol

  2. ruby-on-rails - 用于 Ruby 的 vim 中的全局 "Go to definition"? - 2

    自97年以来我一直在使用vi/vim进行各种快速编辑和管理任务,但最近才考虑使用它来替换Netbeans作为我选择的ruby​​编辑器。我发现一件事在Netbeans和Eclipse中非常有用的是Ctrl+Click“转到定义”功能,您可以在其中按住Ctrl键并单击一个类或方法,然后它将带您了解定义。现在,我玩过丰富的ctags和rails.vim,而且很接近,但没有雪茄。这就是我想要的:默认情况下在Netbeans和Eclipse中,您可以在本地rails中按住ctrl并单击本地方法或类项目,但你也可以ctrl+click定义在gems或用Ruby编写的系统库。以Netbeans为例

  3. ruby-on-rails - Rails 上的 ruby : How to have multiple submit buttons going to different methods (maybe with with_action? ) - 2

    这个问题在这里已经有了答案:HowdoIcreatemultiplesubmitbuttonsforthesameforminRails?(7个答案)关闭9年前。所以..'save'%>'library'%>然后在我的Controller中:with_actiondo|a|a.savedoenda.librarydoendend问题是只有一个操作被调用...两个submit_tags调用相同的操作...知道为什么吗?或者我如何获得两个按钮以将表单提交给两种不同的方法?

  4. DiFi: A Go-as-You-Pay Wi-Fi Access System 精读笔记(三) - 2

    IV.SYSTEMIMPLEMENTATIONWeadoptmodulardesignfollowingtheintegrationofblockchain.Itbringsmoreflexibilitybyseparatingtheimplementationofdifferentfunctionalities,sowecouldleveragetheadvantagesoftheblockchain-basedsmartcontractwhilereducingoverhead.Figure3illustrateshowdifferentmodulesareinvolvedintheint

  5. go-templates - 如何根据表达式有条件地在 Go 模板中设置变量,如果不使用 if 语句包装可能会导致错误 - 2

    问题我该如何做这样的事情:{{$use_ssl:=(ne$.Env.CERT_NAME"")}}其中$.Env.CERT_NAME可能为零/未定义。如果它是零,它给出这个错误:at:errorcallingne:invalidtypeforcomparison注意:我无法控制传递给Go模板的对象,因此必须完全在模板本身内解决这个问题。我尝试过的我试图通过首先检查它是否为非空来变通:{{$use_ssl:=(($.Env.CERT_NAME)&&(ne$.Env.CERT_NAME""))}}但它给出了这个错误:unexpected"&"inoperand所以我切换到这个,这在语法上是允

  6. Go time与string的相爱相杀 - 2

    time包与string包可以说是在Go语言的开发中常用的两个包实际开发过程中(例如web开发)经常会遇到time类型与string类型的交互,计算比较等场景首先来了解GO语言里非常浪漫的一个点,即2006-01-0215:04:05,GO语言诞生的时间,通常用来做时间的格式化time转stringt:=time.Now()//当前时间timeLayoutStr:="2006-01-0215:04:05"t.Format(timeLayoutStr)//返回值为string,可以用一个值来接收它上述例子中,将time类型t转换为string类型,并格式化为年-月-日时-分-秒,这里的格式化是可

  7. ruby-on-rails - 使用 'gem pq' 安装 PostgreSQL gem 失败并出现错误 : Failed to build gem native extension - 2

    我正在学习RubyonRails并尝试开发应用程序。在我的应用程序中,我试图在开发模式下使用默认的SQLite数据库,在生产模式下使用PostgreSQL。但是我在尝试使用安装pggem时遇到以下错误:geminstallpgBuilding native extensions.  This could take a while...ERROR:  Error installing pg:        ERROR: Failed to build gem native extension.     /home/tusharkhatiwada/.rvm/rubies/ruby-2.0.

  8. javascript - 使用哈希 url 卡在 Angular ui-router State.go 上? - 2

    我正在研究ui-router。我有一个状态:.state('new-personal-orders',{url:'/orders/new-personal-orders/:catId?',template:''})在我的Controller中,我可以使用$state.go('new-personal-orders',null,{reload:true})在Html文件中我有一个anchor标记:Link如果标签被点击,状态就会改变,'new-personal-orders'变成当前状态,在url中有尾随散列。然后url看起来像:http://localhost:3000/orders/

  9. 十分钟 Javascript : What is going on in this example code illustrating lazy scoping? - 2

    我一直在重读SpencerTipping的优秀作品JavascriptinTenMinutes在这个使用惰性作用域创建语法宏的示例中,我终究无法弄清楚发生了什么:varf=function(){return$0+$1};varg=eval(f.toString().replace(/\$(\d+)/g,function(_,digits){return'arguments['+digits+']'}));g(5,6);//=>11(exceptonIE)特别是,$0和$1正在被一个函数定义取代——那个函数是如何被计算的?(大概是通过eval(),但我没有看到)。函数中单个下划线参数的用

  10. javascript - 如何用参数做 $state.go() ? - 2

    我已经完美地初始化了$stateProvider并且我正在将所有这些状态与ui-sref一起使用。效果很好。用户按下按钮并通过$stateProvider进入编辑页面。在这个页面上,我有一个执行$http请求的表单:this.pushData=function(data){$http.post('/data/'+$stateParams.dataId+'/otherdata',JSON.stringify({id:otherdata.id,name:otherdata.name}),configAuth).then(functionsuccess(response){varaddedD

随机推荐