duan_88598 2019-05-31 13:50
浏览 76
已采纳

xorm示例不起作用:“运行时错误:无效的内存地址或nil指针取消引用”

Based on this example i tried to write a program that would return some data from a database. Unfortunately, (more-or-less) the same program structure causes memory errors here err := orm.Find(&sensorDataEntry) according to runtime console output.

What am i missing here? Both example and my program has the slice created using make() and uses reference in Find() method.

Code in question:

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    _ "github.com/lib/pq"
    //"database/sql"
    "github.com/go-xorm/xorm"

)

var orm *xorm.Engine

func newRouter() *mux.Router {
    r := mux.NewRouter()
    r.HandleFunc("/sensorentries", GetSensorEntriesHandler).Methods("GET")

    return r
}

type SensorDataEntry struct {
    id int `xorm:"int"`
    sensor_id string `xorm:"varchar(32)"`
    key string `xorm:"varchar(128)"`
    value float64 `xorm:"numeric(20,2)"`
    created_at time.Time `xorm:"timestamp"`
}

func main() {
    connString := "host=server.lan user=x password=x dbname=testdb sslmode=disable"
    orm, err := xorm.NewEngine("postgres", connString)
    //orm.ShowSQL(true)

    if err != nil {
        println(err)
        return
    }

    if err = orm.Sync2(SensorDataEntry{}); err != nil {
        return
    }

    r := newRouter()
    http.ListenAndServe(":8080", r)
}

func GetSensorEntriesHandler(resp http.ResponseWriter, req *http.Request) {
    sensorDataEntry := make([]SensorDataEntry, 0)
    err := orm.Find(&sensorDataEntry)

    if err != nil {
        println(err)
    }

    fmt.Println(sensorDataEntry)

    fmt.Fprintf(resp, "return text")
}
  • 写回答

1条回答 默认 最新

  • drvpvmz16241016 2019-05-31 14:51
    关注

    As noted by mkopriva, the problem was using the same variable name for assignment.

    Solution for the problem was:

    instead of

    orm, err := xorm.NewEngine("postgres", connString)
    

    use

    var err error
    orm, err = xorm.NewEngine("postgres", connString)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化