GORM是一个比较流行且功能齐全的orm库,主要有以下特性
Preload
、Joins
的预加载数据库转struct工具
mysql driver
https://github.com/go-gorm/mysql
gorm 库
https://github.com/go-gorm/gorm
新建一个数据库testdb,建一个members表
CREATE TABLE `members` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '姓名',
`state` tinyint(4) NOT NULL DEFAULT '0' COMMENT '状态(1:有效,0无效,9删除)',
`ctime` int(10) NOT NULL DEFAULT '0' COMMENT '创建时间',
`mtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
go get -u -v github.com/xxjwxc/gormt@master
通过如下命令查查找gormt文件地址
which gormt
和gormt执行文件同目录有个config.yml文件,配置数据库信息
out_dir : "./model" # out dir
url_tag : json # web url tag(json,db(https://github.com/google/go-querystring))
language : # language(English,中 文)
db_tag : gorm # DB tag(gorm,db)
singular_table : true # Table name plural (big Camel-Case):gorm.SingularTable
simple : false #simple output
is_out_sql : false # Whether to output sql
is_out_func : true # Whether to output function
is_foreign_key : true # Whether to mark foreign key or not
is_gui : false # Whether to operate on gui
is_table_name : false # Whether to out GetTableName function
is_null_to_point : false # database is 'DEFAULT NULL' then set element type as point
is_web_tag: false
is_web_tag_pk_hidden: false
db_info :
host : "127.0.0.1"
port : 3306
username : "root"
password : "123456"
database : "testdb"
type: 0 # database type (0:mysql , 1:sqlite , 2:mssql)
执行
./gormt -g=true
这里以mysql库为例
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
创建main.go
package main
import (
"demo/model"
"errors"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
func main() {
//连接数据库
// https://github.com/go-sql-driver/mysql
//dsn := "root:123456@tcp(localhost:3306)/testdb?charset=utf8mb4&parseTime=True&loc=Local"
//db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "root:123456@tcp(localhost:3306)/testdb?charset=utf8mb4&parseTime=True&loc=Local", // data source name, refer https://github.com/go-sql-driver/mysql#dsn-data-source-name
DefaultStringSize: 256, // add default size for string fields, by default, will use db type `longtext` for fields without size, not a primary key, no index defined and don't have default values
DisableDatetimePrecision: true, // disable datetime precision support, which not supported before MySQL 5.6
DontSupportRenameIndex: true, // drop & create index when rename index, rename index not supported before MySQL 5.7, MariaDB
DontSupportRenameColumn: true, // use change when rename column, rename rename not supported before MySQL 8, MariaDB
SkipInitializeWithVersion: false, // smart configure based on used version
}), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
//设置连接池
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
sqlDB, err := db.DB()
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(time.Hour)
//开启debug 控制台输出sql
db=db.Debug()
memberMgr:=model.MembersMgr(db)
//user := model.Members{Name: "haha", Ctime: int(time.Now().Unix()), Mtime: time.Now()}
//result := db.Create(&user) // 通过数据的指针来创建
//fmt.Println(result)
//user.ID // 返回插入数据的主键
//result.Error // 返回 error
//result.RowsAffected // 返回插入记录的条数
//批量插入
//var users = []model.Members{{Name: "haha1",Mtime: time.Now()}, {Name: "haha2",Mtime: time.Now()}, {Name: "haha3",Mtime: time.Now()}}
//db.Create(&users)
//获取单条数据
rows,err:=memberMgr.Get()
fmt.Println(rows)
//获取所有数据
rowArr,err:=memberMgr.Gets()
for _,v:=range rowArr {
fmt.Println(v)
}
members :=&model.Members{}
// 获取第一条记录(主键升序)
db.Where("name = ?", "haha2").First(members)
fmt.Println(members)
//更新
members1:=model.Members{}
// 通过 `RowsAffected` 得到更新的记录数
result := db.Model(members1).Where("name = ?", "haha1").Updates(model.Members{Name: "hello", Mtime: time.Now()})
fmt.Println(result.RowsAffected) // 更新的记录数
fmt.Println(result.Error) // 更新的错误
//删除
//db.Delete(&model.Members{ID:1})
//事务
db.Transaction(func(tx *gorm.DB) error {
// 在事务中执行一些 db 操作(从这里开始,您应该使用 'tx' 而不是 'db')
if err := tx.Create(&model.Members{Name: "Giraffe",Mtime: time.Now()}).Error; err != nil {
// 返回任何错误都会回滚事务
return err
}
if err := tx.Create(&model.Members{Name: "Giraffe",Mtime: time.Now()}).Error; err != nil {
return err
}
// 返回 nil 提交事务
return nil
})
//嵌套事务
user1:=model.Members{Name: "haha2",Mtime: time.Now()}
user2:=model.Members{Name: "haha2",Mtime: time.Now()}
user3:=model.Members{Name: "haha2",Mtime: time.Now()}
db.Transaction(func(tx *gorm.DB) error {
tx.Create(&user1)
tx.Transaction(func(tx2 *gorm.DB) error {
tx2.Create(&user2)
return errors.New("rollback user2") // Rollback user2
})
tx.Transaction(func(tx2 *gorm.DB) error {
tx2.Create(&user3)
return nil
})
return nil
})
}