dosc9472 2014-07-06 05:10
浏览 41
已采纳

与需要清理的对象一起包装

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条回答 默认 最新

  • douci4026 2014-07-06 08:04
    关注

    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().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀