当前位置:网站首页>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
,AfterCreate
establish
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_01
Tosoldier_05
. But becauseBeforeCreate
The existence of methods , In the actual tablename
All 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)
边栏推荐
- QQ computer version cancels escape character input expression
- Dynamic planning solution ideas and summary (30000 words)
- Règlement sur la sécurité des réseaux dans les écoles professionnelles secondaires du concours de compétences des écoles professionnelles de la province de Guizhou en 2022
- [rust notes] 14 set (Part 2)
- leetcode-556:下一个更大元素 III
- Some common problems in the assessment of network engineers: WLAN, BGP, switch
- Currently clicked button and current mouse coordinates in QT judgment interface
- Records of some tools 2022
- 1039 Course List for Student
- [cloud native] record of feign custom configuration of microservices
猜你喜欢
Leetcode-6108: decrypt messages
Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
7. Processing the input of multidimensional features
Leetcode-6110: number of incremental paths in the grid graph
wordpress切换页面,域名变回了IP地址
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
Sqlmap tutorial (1)
Introduction et expérience de wazuh open source host Security Solution
MIT-6874-Deep Learning in the Life Sciences Week 7
MySQL advanced part 2: MySQL architecture
随机推荐
The difference between CPU core and logical processor
Introduction et expérience de wazuh open source host Security Solution
New title of module a of "PanYun Cup" secondary vocational network security skills competition
Some common problems in the assessment of network engineers: WLAN, BGP, switch
Shutter web hardware keyboard monitoring
【Rust 笔记】16-输入与输出(下)
1041 Be Unique
Flutter Web 硬件键盘监听
Appium基础 — 使用Appium的第一个Demo
QQ computer version cancels escape character input expression
One question per day 2047 Number of valid words in the sentence
Erreur de connexion Navicat à la base de données Oracle Ora - 28547 ou Ora - 03135
QQ电脑版取消转义符输入表情
RGB LED infinite mirror controlled by Arduino
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
【LeetCode】Day95-有效的数独&矩阵置零
leetcode-3:无重复字符的最长子串
数据可视化图表总结(二)
数据可视化图表总结(一)
Leetcode-6109: number of people who know secrets