参考:
http://books.studygolang.com/gorm/models.html(api)
https://gorm.io/driver/mysql(官方)
引入包
import ( "gorm.io/driver/mysql" "gorm.io/gorm" )
连接数据库
//基本 dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) //更多选项 db, err := gorm.Open(mysql.New(mysql.Config{ DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // data source name DefaultStringSize: 256, // default size for string fields DisableDatetimePrecision: true, // disable datetime precision, which not supported before MySQL 5.6 DontSupportRenameIndex: true, // drop & create when rename index, rename index not supported before MySQL 5.7, MariaDB DontSupportRenameColumn: true, // `change` when rename column, rename column not supported before MySQL 8, MariaDB SkipInitializeWithVersion: false, // auto configure based on currently MySQL version }), &gorm.Config{})
连接池
参考:https://www.cnblogs.com/frankfud/p/13605842.html
GORM using database/sql to maintain connection pool
sqlDB, err := db.DB() // SetMaxIdleConns sets the maximum number of connections in the idle connection pool. sqlDB.SetMaxIdleConns(10) // SetMaxOpenConns sets the maximum number of open connections to the database. sqlDB.SetMaxOpenConns(100) // SetConnMaxLifetime sets the maximum amount of time a connection may be reused. sqlDB.SetConnMaxLifetime(time.Hour)
原生sql
参考:https://gorm.io/docs/sql_builder.html
ddl数据定义:数据库,表,字段,索引
参考:https://gorm.io/docs/migration.html
dml和dql:curd
参考:https://gorm.io/docs/create.html
TCL:事务
参考:https://gorm.io/docs/transactions.html