这是mysql driver的bug吗?

package main

import(
"database/sql"

_ "github.com/go-sql-driver/mysql"
)

func main() {
db, err := sql.Open("mysql", ":@tcp(:0)/?charset=utf8")
if err != nil {
panic(err)
}
db.Close()
}

我使用空的参数竟然连接mysql成功了,而且我本机并没有监听3306端口。


go version: 1.7.4 windows10/amd64
go-sql-driver version: 1.3

已邀请:

stevewang

赞同来自:

是database/sql本身流程的问题。
因为sql.Open里还没有执行driver相关的代码。


官方文档里有提到“Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.”
不过其实这里的代码实现中并没有进行参数检查。
也许对于不同类型的数据库进行统一参数检查比较困难?

qiangmzsx - 痛而不言,笑而不语,迷而不失,惊而不乱。

赞同来自:

遇到这个问题很正常的,我们需要去看看代码:
sql.Open("mysql", ":@tcp(:0)/?charset=utf8")


// Open opens a database specified by its database driver name and a
// driver-specific data source name, usually consisting of at least a
// database name and connection information.
//
// Most users will open a database via a driver-specific connection
// helper function that returns a *DB. No database drivers are included
// in the Go standard library. See https://golang.org/s/sqldrivers for
// a list of third-party drivers.
//
// Open may just validate its arguments without creating a connection
// to the database. To verify that the data source name is valid, call
// Ping.
//
// The returned DB is safe for concurrent use by multiple goroutines
// and maintains its own pool of idle connections. Thus, the Open
// function should be called just once. It is rarely necessary to
// close a DB.
func Open(driverName, dataSourceName string) (*DB, error) {
driversMu.RLock()
driveri, ok := drivers[driverName]
driversMu.RUnlock()
if !ok {
return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
}
db := &DB{
driver: driveri,
dsn: dataSourceName,
openerCh: make(chan struct{}, connectionRequestQueueSize),
lastPut: make(map[*driverConn]string),
connRequests: make(map[uint64]chan connRequest),
}
go db.connectionOpener()
return db, nil
}

其中有:

// Open may just validate its arguments without creating a connection
// to the database. To verify that the data source name is valid, call
// Ping.


Open 可能只是验证这些参数,并不会去连接database,要验证这个连接是否成功,使用ping()方法

要回复问题请先登录注册