无法返回数据库对象。

huangapple go评论81阅读模式
英文:

Cannot return database object.

问题

这是我用于与PostgreSQL数据库一起工作的代码。

package main

import (
    "database/sql"
    _ "github.com/lib/pq"
    "fmt"
    "log"
)

//连接所需的详细信息
const (
    HOST     = "主机名"
    USER     = "用户名"
    PASSWORD = "密码"
    DATABASE = "数据库"
)

func Create() (*sql.DB) {

    dbinfo := fmt.Sprintf("host=%s user=%s password=%s dbname=%s", HOST, USER, PASSWORD, DATABASE)
    db,err  := sql.Open("postgres", dbinfo)
    defer db.Close()

    if (err != nil) {
        log.Fatal(err)
    }

    err = db.Ping()

    if err != nil {
      log.Fatal(err)
    }

    return db
}


func main() {
    db := Create()
    querStmt, err := db.Prepare("select count(*) from table")

    if err != nil {
        fmt.Printf("无法准备查询\n")
        log.Fatal(err)
    }
    res, err := querStmt.Exec()
    if err != nil {
        fmt.Printf("无法执行查询\n")
        log.Fatal(err)
    }

    fmt.Printf("%v\n", res)
}

运行此代码时,我遇到了以下错误:

无法准备查询
2016/03/09 16:57:23 sql: database is closed

如果我从Create()函数中运行查询,则可以正常工作,但是在main()函数中使用Create()返回的db对象进行相同操作时却不起作用。谢谢帮助。

英文:

This is my code for working with postgres database.

package main

import (
    "database/sql"
    _ "github.com/lib/pq"
    "fmt"
    "log"
)

//Details required for connection
const (
    HOST     = "HOSTNAME"
    USER     = "USER"
    PASSWORD = "PASSWORD"
    DATABASE = "DB"
)

func Create() (*sql.DB) {

    dbinfo := fmt.Sprintf("host=%s user=%s password=%s dbname=%s", HOST, USER, PASSWORD, DATABASE)
    db,err  := sql.Open("postgres", dbinfo)
    defer db.Close()

    if (err != nil) {
        log.Fatal(err)
    }

    err = db.Ping()

    if err != nil {
      log.Fatal(err)
    }

    return db
}


func main() {
    db := Create()
    querStmt, err := db.Prepare("select count(*) from table")

    if err != nil {
        fmt.Printf("Cannot prepare query\n")
        log.Fatal(err)
    }
    res, err := querStmt.Exec()
    if err != nil {
        fmt.Printf("Cannot execute query\n")
        log.Fatal(err)
    }

    fmt.Printf("%v\n", res)
}

When running this code i am getting this error

Cannot prepare query
2016/03/09 16:57:23 sql: database is closed

If i run query from Create() then it works perfectly but doing same on db object returned by Create() inside main() is not working. Thanks for help.

答案1

得分: 3

你从Create返回时,数据库就关闭了,因为你的defer语句在Create内部而不是在main内部。将defer语句移到main中,它应该按预期工作。

英文:

Your database is closed the moment you return from Create because your defer is inside it and not inside main. Move the defer to main and it should work as intended.

huangapple
  • 本文由 发表于 2016年3月10日 00:30:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/35897251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定