为什么sql.Open()返回nil作为错误,当它不应该? [英] Why does sql.Open() return nil as error when it should not?
问题描述
我试图看看如果我给了它错误的连接信息,但是它会返回 nil
为错误。即使我完全关闭了mysql,它仍然不会返回错误。如果这个函数没有返回错误,那么在这个函数后面检查错误的点是什么?
这是在Windows上,我使用XAMPP并且没有密码为数据库。用户名是root
。
import(
数据库/ sql
日志
_github.com/go-sql-driver/mysql
)
func main() {
db,err:= sql.Open(mysql,root @ tcp(127.0.0.1:3306)/ dbname?charset = utf8)
if err!= nil {
log.Fatal(err)
}
defer db.Close()
}
<解决方案SQL.Open只创建DB对象,但没有打开与数据库的任何连接。如果你想测试你的连接,你必须执行查询来强制打开一个连接。常用的方法是在您的DB对象上调用Ping()。
请参阅 http://golang.org/pkg/database/sql/#Open 和 http://golang.org/pkg/database/sql/#DB.Ping
I am trying to connect to a mysql database.
I tried to see if I would get an error if I gave it wrong connection information but it still returns nil
as error. Even If I shut down mysql completely it still does not return an error. What is the point of check for errors after this function if it does not return errors?
This is on Windows, I am using XAMPP and I don't have a password for the database. Username is "root"
.
import (
"database/sql"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root@tcp(127.0.0.1:3306)/dbname?charset=utf8")
if err != nil {
log.Fatal(err)
}
defer db.Close()
}
SQL.Open only creates the DB object, but dies not open any connections to the database. If you want to test your connections you have to execute a query to force opening a connection. The common way for this is to call Ping() on your DB object.
See http://golang.org/pkg/database/sql/#Open and http://golang.org/pkg/database/sql/#DB.Ping
这篇关于为什么sql.Open()返回nil作为错误,当它不应该?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!