go lang连接mysql数据库,golang本身没有提供连接mysql的驱动
需要包
“database/sql”
以及下载所需要的包
“github.com/go-sql-driver/mysql”
package mainimport ( _"database/sql" _ "fmt" _ "github.com/go-sql-driver/mysql" "fmt" "database/sql")func main() { db, err := sql.Open("mysql", "usename:password@/dbname")//对应数据库的用户名和密码以及数据库名 defer db.Close() if err != nil { panic(err) } else { fmt.Println("success") } rows, err := db.Query("SELECT name FROM extra_baidu_qi_add_mid_01") if err != nil { panic(err) return } for rows.Next() { var name string err = rows.Scan(&name) if err != nil { panic(err) } fmt.Println(name) } }
其中连接参数可以有如下几种形式:
user@unix(/path/to/socket)/dbname?charset=utf8
user:password@tcp(localhost:5555)/dbname?charset=utf8
user:password@/dbname
user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname
下载驱动
sudo go get github.com/go-sql-driver/mysql
如果提示这样的失败信息:cannot download, $GOPATH not set. For more details see: go help gopath,可以使用如下命令解决
sudo env GOPATH=/Users/chenjiebin/golang go get github.com/go-sql-driver/mysql
GOPATH的值根据自行环境进行替换。