如何使用Go和go-sql-driver连接到mysql服务器?

时间:2013-07-09 23:53:49

标签: mysql go

我正在关注教程herehere,但我无法连接到mySQL安装附带的test数据库。我可以通过命令行连接到mySql。我错过了什么?当我运行下面的代码时,我收到错误“无法ping”:

package main

import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "/test")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        fmt.Println("cannot ping")
        return
    } 
}

1 个答案:

答案 0 :(得分:2)

例如,将{MySQL}用户名和密码替换为userpassword

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "user:password@/test")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()
    err = db.Ping()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Ping")
}

输出:

Ping