<p>I am probably making some stupid mistake but I am quite baffled by the
following code:</p>
<pre><code>func main() {
db, err := sql.Open("postgres", "user=gouser password=gouser dbname=myDB sslmode=disable")
if err != nil {
log.Fatal("Connection with the DB broken: %s",err)
}
}
</code></pre>
<p>Suppose I am using the wrong user/password/dbname: sql.Open always
reported that err is <strong>nil</strong>. Why? I would expect to get an error of some
sort, in case I mess up with the DSN parameteres.</p>
<p>On the other hand, I am able to get an error report when using a 'Ping'
function:</p>
<pre><code>err = db.Ping()
if err != nil {
log.Fatal("Error: Could not establish a connection with the database")
}
</code></pre>
<p>Which is also reported on the PgSQL error log. What is wrong in getting
the 'err' after sql.Open? Why is always empty?</p>
<hr/>**评论:**<br/><br/>cs-guy: <pre><p>At present sql.Open will only return an error if you ask it for a driver that isn't available.</p>
<p>Keep in mind that the *sql.DB that sql.Open returns represents a connection pool. When first created, the connection pool is empty. You won't see connection related errors until you perform an operation that must connect to the database. The Ping method simply attempts to get a connection from the pool and put it back, and is thus the simplest operation that forces an actual connection to the database.</p></pre>dsmt76: <pre><p>Thanks, you are absolutely right. I should have checked twice the Go Database
documentation, it is written explicitely there: <a href="http://go-database-sql.org/accessing.html" rel="nofollow">Go Database SQL</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传