当前位置:网站首页>11-gorm-v2-02-create data
11-gorm-v2-02-create data
2022-07-05 06:15:00 【Operation and maintenance xuandegong】
List of articles
1. A simple example
db.Create(&liuBei)
- Complete example
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:[email protected](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. Create a record with the specified field
- Use the specified field
db.Select("name").Create(&liuBei)
- Exclude the specified fields
db.Omit("name").Create(&liuBei)
3. Batch insert
3.1 Create with array slices
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)
}
- Output
OK
[{
8 28 LiuBei} {
9 22 GuanYu} {
10 20 ZhangFei}]
- Database table results
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 Batch creation
The test was not successful , Will still create 5 Data .
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. Create hook
4.1 Concept
GORM Allow user-defined hooks
BeforeSave,BeforeCreate,AfterSave,AfterCreateestablish
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
u.Name = "Shi_Bing"
return
}
4.2 Complete example
- Code
In the example, a table is created by slicing , Ought to be
soldier_01Tosoldier_05. But becauseBeforeCreateThe existence of methods , In the actual tablenameAll of themshi_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:[email protected](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
}
- Output
OK
[{
16 0 Shi_Bing} {
17 0 Shi_Bing} {
18 0 Shi_Bing} {
19 0 Shi_Bing} {
20 0 Shi_Bing}]
- Database table
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 Skip hook
SkipHooks Session mode can skip hooks .
db.Session(&gorm.Session{
SkipHooks: true}).Create(&user)
5. according to MAP establish
user := map[string]interface{
}{
"Name":"GuanYu",
"Age":22,
}
db.Model(&User{
}).Create(user)
边栏推荐
- Leetcode-556: the next larger element III
- QQ电脑版取消转义符输入表情
- [rust notes] 14 set (Part 1)
- SQLMAP使用教程(一)
- 1.13 - RISC/CISC
- 对for(var i = 0;i < 5;i++) {setTimeout(() => console.log(i),1000)}的深入分析
- [rust notes] 17 concurrent (Part 1)
- Traditional databases are gradually "difficult to adapt", and cloud native databases stand out
- Appium自动化测试基础 — Appium测试环境搭建总结
- Quickly use Amazon memorydb and build your own redis memory database
猜你喜欢

LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树

Introduction and experience of wazuh open source host security solution

Matrixdb V4.5.0 was launched with a new mars2 storage engine!

MIT-6874-Deep Learning in the Life Sciences Week 7

可变电阻器概述——结构、工作和不同应用

数据可视化图表总结(一)

SQLMAP使用教程(二)实战技巧一

LeetCode 0107.二叉树的层序遍历II - 另一种方法

RGB LED infinite mirror controlled by Arduino

Erreur de connexion Navicat à la base de données Oracle Ora - 28547 ou Ora - 03135
随机推荐
leetcode-22:括号生成
剑指 Offer II 058:日程表
leetcode-9:回文数
1.14 - assembly line
New title of module a of "PanYun Cup" secondary vocational network security skills competition
1039 Course List for Student
A reason that is easy to be ignored when the printer is offline
Appium基础 — 使用Appium的第一个Demo
927. Trisection simulation
Daily question 2013 Detect square
1039 Course List for Student
Groupbykey() and reducebykey() and combinebykey() in spark
WordPress switches the page, and the domain name changes back to the IP address
leetcode-6111:螺旋矩阵 IV
Leetcode-6111: spiral matrix IV
Open source storage is so popular, why do we insist on self-development?
Network security skills competition in Secondary Vocational Schools -- a tutorial article on middleware penetration testing in Guangxi regional competition
One question per day 1765 The highest point in the map
[rust notes] 14 set (Part 2)
【Rust 笔记】16-输入与输出(上)