Closing sql connection

xuanbao · · 476 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi, was wondering what is the best approach for handling sql connections, create a new connection by request and closing it using defer, or have a singleton during the program lifetime at package level and only closing it when the app is shutting down.</p> <hr/>**评论:**<br/><br/>soapysops: <pre><p>I&#39;m a little confused by your terminology - what are you referring to when you say &#34;connection&#34;? You should not ever really be managing database connections yourself.</p> <p>If you&#39;re talking about the <code>sql.DB</code>, you should only be initializing that object once, near the start of the program after you&#39;ve loaded configuration. Then Go will take care of managing actual SQL database connections for you. You should not manage them yourself unless you have a very special case or a database driver bug. You probably don&#39;t even need to close the connection yourself (although it is good housekeeping).</p> <p>If you&#39;re talking about database transactions, most people will open one at the start of a request handler and commit or rollback at the end, but it really depends on how you want to do isolation. (If you don&#39;t completely know what that means, it&#39;s okay, but you should do some more research on relational database basics until you do understand, because it&#39;s important.)</p></pre>vfedoroff: <pre><p>My favorite approach is the connection management per request. On the beginning of the request you open a connection, on the end back connection to the pool. </p></pre>kardianos: <pre><p>Use the context method variants of sql.DB, pass in a request scoped context, and they will return when the request is done.</p></pre>jjzcru: <pre><p>Yes, by connection I mean the sql.DB, so your recommendation is to have a singleton that lives during the application lifetime </p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

476 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传