0

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It was a go noob mistake :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.