<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'm a little confused by your terminology - what are you referring to when you say "connection"? You should not ever really be managing database connections yourself.</p>
<p>If you're talking about the <code>sql.DB</code>, you should only be initializing that object once, near the start of the program after you'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't even need to close the connection yourself (although it is good housekeeping).</p>
<p>If you'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't completely know what that means, it's okay, but you should do some more research on relational database basics until you do understand, because it'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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传