02-创建数据
目录
1. 简单示例
db.Create(&liuBei)
- 完整示例
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type User struct {
ID int64
Age int64
Name string
}
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
liuBei := User{
Name: "LiuBei",
Age: 28,
}
db.Create(&liuBei)
}
func connect() (db *gorm.DB,sqlDB *sql.DB,err error) {
dsn := "root:40010355@tcp(127.0.0.1:3306)/crow?charset=utf8&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
sqlDB,_ = db.DB()
if err != nil {
fmt.Printf(err.Error())
defer sqlDB.Close()
}else {
fmt.Printf("OK\n")
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
}
return
}
2. 用指定的字段创建记录
- 使用指定字段
db.Select("name").Create(&liuBei)
- 排除指定字段
db.Omit("name").Create(&liuBei)
3. 批量插入
3.1 用数组切片创建
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var users = []User{{Name: "LiuBei",Age: 28}, {Name: "GuanYu",Age: 22}, {Name: "ZhangFei",Age: 20}}
db.Create(&users)
fmt.Println(users)
}
- 输出
OK
[{8 28 LiuBei} {9 22 GuanYu} {10 20 ZhangFei}]
- 数据库表结果
mysql> select * from users;
+----+------+----------+
| id | age | name |
+----+------+----------+
| 8 | 28 | LiuBei |
| 9 | 22 | GuanYu |
| 10 | 20 | ZhangFei |
+----+------+----------+
3 rows in set (0.00 sec)
3.2 CreateInBatches 批量创建
测试未成功,依然会创建5条数据。
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
//db.Migrator().CreateTable(&User{})
user := []User{{Name: "soldier_01"},{Name: "soldier_02"},{Name: "soldier_03"},{Name: "soldier_04"},{Name: "soldier_05"}}
db.CreateInBatches(user, 3)
}
4. 创建钩子
4.1 概念
-
GORM 允许用户定义的钩子
BeforeSave
,BeforeCreate
,AfterSave
,AfterCreate
-
创建
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
u.Name = "Shi_Bing"
return
}
4.2 完整示例
- 代码
示例中通过切片创建表,本应是
soldier_01
到soldier_05
。但因为BeforeCreate
方法的存在,实际表中name
列都是shi_bing
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type User struct {
ID int64
Age int64
Name string
}
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
u.Name = "Shi_Bing"
return
}
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
user := []User{{Name: "soldier_01"},{Name: "soldier_02"},{Name: "soldier_03"},{Name: "soldier_04"},{Name: "soldier_05"}}
db.Create(&user)
fmt.Println(user)
}
func connect() (db *gorm.DB,sqlDB *sql.DB,err error) {
dsn := "root:40010355@tcp(127.0.0.1:3306)/crow?charset=utf8&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
sqlDB,_ = db.DB()
if err != nil {
fmt.Printf(err.Error())
defer sqlDB.Close()
}else {
fmt.Printf("OK\n")
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
}
return
}
- 输出
OK
[{16 0 Shi_Bing} {17 0 Shi_Bing} {18 0 Shi_Bing} {19 0 Shi_Bing} {20 0 Shi_Bing}]
- 数据库表
mysql> select * from users;
+----+------+----------+
| id | age | name |
+----+------+----------+
| 16 | 0 | Shi_Bing |
| 17 | 0 | Shi_Bing |
| 18 | 0 | Shi_Bing |
| 19 | 0 | Shi_Bing |
| 20 | 0 | Shi_Bing |
+----+------+----------+
5 rows in set (0.00 sec)
4.3 跳过钩子
SkipHooks 会话模式可以跳过钩子。
db.Session(&gorm.Session{SkipHooks: true}).Create(&user)
5. 根据MAP 创建
user := map[string]interface{}{
"Name":"GuanYu",
"Age":22,
}
db.Model(&User{}).Create(user)