需要清理的对象的包

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

package with objects that need cleanup

问题

我正在尝试将我的数据库代码分组到一个子包中,这样可以封装我的数据库连接和所有的预处理语句。

我可以在包的init函数中创建数据库连接和语句,但是我需要在某个时候关闭它们。

在一个程序中,这些变量是在使用它们的代码中初始化的,我会使用defer db.Close()等方式,但是在这里该怎么做呢?

我希望不暴露包的全局变量(连接和语句),这样调用者就无法访问它们以关闭它们。有没有一种更优雅的方法来做到这一点?

我怀疑我可能有一个错误的范例在脑海中,我试图在一种没有对象的语言中创建对象(本质上就是这样)。如果是这样的话,我将非常感谢任何关于如何以Go的方式做到这一点的帮助。

package database

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

var db *sql.DB
var stmtSelectUser *sql.Stmt

func GetUser(email string) string {
  var name string
  stmtSelectUser.QueryRow(email).Scan(&name)
  return name
}

func init() {
  var e error
  db, e = sql.Open("postgres", "host=localhost dbname=pictocat sslmode=disable")
  stmtSelectUser, e = db.Prepare("select * from users where email='$1'")
}
英文:

I am trying to group my database code into a sub-package, which would sort of encapsulate my database connection and all my prepared statements.

I can create the database connection and the statements in the package's init function, but I need to close them at some point.

In a program, where these variables are initialized in the code that uses them I would use defer db.Close(), etc, but how to go about this here?

I would prefer not to expose the package's global variables (connection and statements) so that the caller could access them to close them. Is there a way to do it in a more elegant manner?

I suspect that I might have a wrong paradigm in mind, and I am trying to create objects (this is essentially what it is here) in a language that does not have them. If so then I would appreciate any help with how to do it go-way.

package database

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

var db *sql.DB
var stmtSelectUser *sql.Stmt

func GetUser(email string) string {
  var name string
  stmtSelectUser.QueryRow(email).Scan(&name)
  return name
}

func init() {
  var e error;
  db, e = sql.Open("postgres", "host=localhost dbname=pictocat sslmode=disable")
  stmtSelectUser, e = db.Prepare("select * from users where email='$1'")
}

答案1

得分: 0

从你的示例代码中并不清楚你的问题是什么,但一般来说:

要么运行语句的函数需要完成语句并关闭它,要么你需要在你的包中添加一个函数,以便调用者可以关闭它;就是这么简单。

你不需要在你的包中暴露所有的数据库内容,只需要一个函数,该函数再调用Close()。

英文:

It's not really clear from your example code what your problem is, but in general:

Either the function running a statement needs to finish the statement and Close() it or you need to add a function to your package so the caller can close it; it's as simple as that.

You don't need to expose all of the database stuff in your package, just a function that in turns calls Close().

huangapple
  • 本文由 发表于 2014年7月6日 13:10:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/24592898.html
匿名

发表评论

匿名网友

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

确定