connect mysql over

main
Your Name 2024-07-18 00:51:24 +08:00
parent 1663759709
commit 8af13f9163
4 changed files with 47 additions and 1 deletions

5
go.mod
View File

@ -1,3 +1,8 @@
module course
go 1.22
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/go-sql-driver/mysql v1.8.1 // indirect
)

4
go.sum Normal file
View File

@ -0,0 +1,4 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=

View File

@ -0,0 +1,29 @@
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()
}

View File

@ -31,4 +31,12 @@ SQL慢查询优化
运维相关
MYSQL主从
binlog
MYSQL读写分离
MYSQL读写分离
golang 的database/sql 原生支持链接池,是并发安全的
这个标准库没有具体的实现,只是列出了一些第三方库需要实现的内容
下载驱动
go get -u github.com/go-sql-driver/mysql
导入驱动