pq QueryRow扫描失败,内存地址无效或取消了nil指针的引用

时间:2020-04-17 13:06:38

标签: go pq

我具有以下功能,应该从我的想法表中检索一行:

func (s *IdeaService) GetIdea(id int64) (*ideaservice.Idea, error) {
    stmt, err := s.DB.Prepare("SELECT id, name, description, created_on, last_updated FROM ideas WHERE id = $1")
    if err != nil {
        return nil, err
    }
    defer stmt.Close()
    var idea *ideaservice.Idea
    err = stmt.QueryRow(id).Scan(&idea.ID, &idea.Name, &idea.Description, &idea.CreatedOn, &idea.LastUpdated)
    return idea, err
}

当我在测试中运行它时,发生以下错误:

--- FAIL: TestGetIdea (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x65be98]

我似乎无法弄清楚问题所在。我相信我已经正确地将var实例化为一个指针,然后在Scan方法中将其赋值。有人有建议吗?

1 个答案:

答案 0 :(得分:0)

func (s *IdeaService) GetIdea(id int64) (*ideaservice.Idea, error) {
    stmt, err := s.DB.Prepare("SELECT id, name, description, created_on, last_updated FROM ideas WHERE id = $1")
    if err != nil {
        return nil, err
    }
    defer stmt.Close()
    var idea *ideaservice.Idea
    err = stmt.QueryRow(id).Scan(&idea.ID, &idea.Name, &idea.Description, &idea.CreatedOn, &idea.LastUpdated)
    return idea, err
}

是否可以将$1替换为?,看看是否可行?在stmt.QueryRow中,您要传递id。像这样:

stmt, err := s.DB.Prepare("SELECT id, name, description, created_on, last_updated FROM ideas WHERE id = ?")

如果它不起作用,请添加以下代码段:

switch {
    case err == sql.ErrNoRows:
        log.Fatalf("no user with id %d", id)
    case err != nil:
        log.Fatal(err)
    default:
        log.Println("ok!")
    }

更新:没有看到有关该问题的评论。是的,他也是正确的。还要修复它们。

然后检查err被困的位置(在这种情况下)。