course/mysql/golangconnectmysql.go

30 lines
652 B
Go
Raw Normal View History

2024-07-18 00:51:24 +08:00
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql" //自动执行init()
"log"
)
// go链接mysql示例
func main() {
//数据库信息
dsn := "root:123456@tcp(43.143.245.135:3306)/wangaodev"
//连接数据库
db, err := sql.Open("mysql", dsn) //不会校验用户名和密码是否正确
if err != nil {
//dsn 格式不正确会报错
log.Fatalf("dsn:%s invalid ,err%v\n", dsn, err)
return
}
//校验用户名和密码是否正确
//尝试连接数据库
err = db.Ping()
if err != nil {
log.Fatalf("open %s failed,err%v\n", dsn, err)
return
}
log.Printf("connect %s success.\n", dsn)
defer db.Close()
}