Gorm
依赖
go get -u gorm.io/driver/mysql
go get -u gorm.io/gorm
注意
案例
func TestGormConn(t *testing.T) {
dsn := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8"
//这是对mysql的配置进行统一
mysqlConfig := mysql.Config{
DSN: dsn, // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
SkipInitializeWithVersion: false, // 根据版本自动配置
}
//可以用mysql.New(),当然也可以用mysql.Open(dsn)
db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{})
if err != nil {
fmt.Println("连接失败")
}
if err != nil {
fmt.Println("连接错误")
}
fmt.Println(db)
}
Xorm
依赖
go get -u xorm.io/xorm
案例
Engine 引擎
func TestXormConn(t *testing.T) {
dataSource := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8"
//这是单个引擎的案例
engine, err := xorm.NewEngine("mysql", dataSource)
if err != nil {
fmt.Println("连接失败")
}
err = engine.Ping()
if err != nil {
fmt.Println("连接错误")
}
defer engine.Close()
}
Engine Group 引擎
func TestXormGroupConn(t *testing.T) {
conns := []string{
"root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8;",
"root:123456@tcp(127.0.0.1:3306)/test_db1?charset=utf8;",
"root:123456@tcp(127.0.0.1:3306)/test_db2?charset=utf8;",
}
engine, err := xorm.NewEngineGroup("mysql", conns)
if err != nil {
fmt.Println("连接失败")
}
err = engine.Ping()
if err != nil {
fmt.Println("连接错误")
}
}