<p>When creating a database handle, where the the variable 'db' is declared outside of main, why does this produce a panic: </p>
<pre><code>db, err := sql.Open("mysql", "user:pass@unix(/path/mysqld.sock)/dbname")
</code></pre>
<p>but this doesn't: </p>
<pre><code>var err error
db, err = sql.Open("mysql", "user:pass@unix(/path/mysqld.sock)/dbname")
</code></pre>
<p>the panic is a nil pointer dereference when the first query is run. </p>
<hr/>**评论:**<br/><br/>pdffs: <pre><p>I'm fairly sure this exact piece of code is not what's causing your problem, you may need to provide more context.</p></pre>earthboundkid: <pre><p>Sounds like a scope error. Probably DB is both a package variable and a function variable but without context that’s just a guess. </p></pre>GunsKnivesRadios: <pre><p>Or something even dumber. I cut it down to just enough code to make a database handle and run a query and now I can't reproduce it, go figure.</p>
<p>Thanks for the help though, both of you. </p></pre>tgulacsi: <pre><p>I'm sure you had db var declared global, so with := you created a local db var, and didn't touch the global, which remained nil.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传