Baffled by sql.Open: err is always nil

polaris · · 428 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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(&#34;postgres&#34;, &#34;user=gouser password=gouser dbname=myDB sslmode=disable&#34;) if err != nil { log.Fatal(&#34;Connection with the DB broken: %s&#34;,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 &#39;Ping&#39; function:</p> <pre><code>err = db.Ping() if err != nil { log.Fatal(&#34;Error: Could not establish a connection with the database&#34;) } </code></pre> <p>Which is also reported on the PgSQL error log. What is wrong in getting the &#39;err&#39; 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&#39;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&#39;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

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