英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论