Preface
最近在做一系列的准备工作,包括 Golang 和很多软件以及工具的配合。
今天是测试连接之前搭建好的 mysql 容器。
由于 go-sql-driver/mysql 的文档比较晦涩,所以需要通过阅读源码配合文档来进行测试,所以才有此记录的必要。
Dependency
go-sql-driver
1
| go get -u github.com/go-sql-driver/mysql
|
go-sql-driver:Github
go-sql-driver:GoDoc
Test Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package test
import ( "database/sql" "fmt" "github.com/go-sql-driver/mysql" "testing" "time" )
func TestMysql(t *testing.T) { config := mysql.NewConfig() config.User = "root" config.Passwd = "12345" config.Net = "tcp" config.Addr = "192.168.2.127" config.ReadTimeout = time.Second * 5 config.WriteTimeout = time.Second * 5 config.Timeout = time.Second * 5 dnsstr := config.FormatDSN()
db, err := sql.Open("mysql", dnsstr) if err != nil { fmt.Println("Error on conntecting : ", err) t.FailNow() } defer db.Close()
err = db.Ping() if err != nil { fmt.Println("Error on ping : ", err) t.FailNow() } }
|
Result
1 2 3 4 5
| === RUN TestMysql --- PASS: TestMysql (0.00s) PASS
Process finished with exit code 0
|