doukuo9116 2015-11-07 03:38 采纳率: 100%
浏览 15
已采纳

我应该在程序中多久调用一次sql.Open?

As the title says I don't know if having multiple sql.Open statements is a good or bad thing or what or if I should have a file with just an init that is something like:

var db *sql.DB


func init() {
    var err error
    db, err = sql.Open
}

just wondering what the best practice would be. Thanks!

  • 写回答

1条回答 默认 最新

  • dongtingrun4973 2015-11-07 03:43
    关注

    You should at least check the error.
    As mentioned in "Connecting to a database":

    Note that Open does not directly open a database connection: this is deferred until a query is made. To verify that a connection can be made before making a query, use the Ping function:

    if err := db.Ping(); err != nil {
      log.Fatal(err)
    }
    

    After use, the database is closed using Close.

    If possible, limit the number of opened connection to a database to a minimum.
    See "Go/Golang sql.DB reuse in functions":

    You shouldn't need to open database connections all over the place.
    The database/sql package does connection pooling internally, opening and closing connections as needed, while providing the illusion of a single connection that can be used concurrently.

    As elithrar points out in the comment, database.sql/#Open does mention:

    The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections.
    Thus, the Open function should be called just once.
    It is rarely necessary to close a DB.

    As mentioned here

    Declaring *sql.DB globally also have some additional benefits such as SetMaxIdleConns (regulating connection pool size) or preparing SQL statements across your application.

    You can use a function init, which will run even if you don't have a main():

    var db *sql.DB
    func init() {
        db, err = sql.Open(DBparms....)
    }
    

    init() is always called, regardless if there's main or not, so if you import a package that has an init function, it will be executed.
    You can have multiple init() functions per package, they will be executed in the order they show up in the code (after all variables are initialized of course).

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

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证