doumianfeng5065 2014-12-02 03:03 采纳率: 0%
浏览 397
已采纳

Golang SQL数据库打开和关闭

In Go database/sql package it says it is rare to close the database with db.Close because it is meant to be shared by many go routines. Then which one is better when we are given 100 functions that queries from a same data:

  1. Open the database inside each function
  2. Open the database only one time and use the same connection for every 100 function.

1 is easier because if one fails other 99 can still be working. And no need to pass database connection arguments. But in performance wise which one is better?

  • 写回答

1条回答 默认 最新

  • doulun9534 2014-12-02 03:30
    关注

    You missed an important part of what the documentation says:

    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.

    (emphasis mine)

    So, your option #2 doesn't actually make sense. The connections are pooled - so use the same connection for every 100 function doesn't apply. Also, option #1 is a waste of time - just do it once as the documentation states, but call Ping after you do just to make sure everything is fine (and have it actually attempt to connect to the database - regardless of driver).

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度