GORM是一個比較流行且功能齊全的orm庫,主要有如下特性mysql
Preload
、Joins
的預加載數據庫轉struct工具git
mysql drivergithub
https://github.com/go-gorm/mysqlgolang
gorm 庫web
https://github.com/go-gorm/gormsql
新建一個數據庫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文件地址json
which gormt
和gormt執行文件同目錄有個config.yml文件,配置數據庫信息tcp
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 }) }