当前位置:网站首页>11-grom-v2-05-initialization
11-grom-v2-05-initialization
2022-07-03 20:08:00 【Operation and maintenance xuandegong】
List of articles
1. FirstOrInit
Be careful
:FirstOrInit
It will only be assigned to the structure , Instead of writing to the table FirstOrCreate
Will be written into the table
1.1 Basic use
1.1.1 Instructions
Look up the table according to the parameters ,
find out , Then assign a value to the structure ;
We didn't find it , The structure can only get the value of the query condition .
db.FirstOrInit(&user, User{
Name: "LiuBei"})
1.1.2 Complete example
- Code
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type User struct {
ID int64
Age int64
Name string
Email string
Company string
}
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var user User
db.FirstOrInit(&user, User{
Name: "LiuBei"})
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
}
find out , Then assign the result to the structure :
OK
{
1 28 LiuBei [email protected] shu}
Not found , Then he only gets the value of the query condition :
{
0 0 LiuBei }
1.2 Attrs ( If no result is found, give Struct assignment )
1.2.1 Instructions
Attrs
Written in FirstOrInit
front , When FirstOrInit
When no result is found , Will receive Attrs
Parameter data of
db.Attrs(GuanYu).FirstOrInit(&user, User{
Name: "GuanYu"})
1.2.2 Example
Ideas
Define a structureGuanYu
, And the assignment , toAttrs
call .
Define a structureuser
toFirstOrInit
Call to receive data .
Define a structure , And the assignment , toFirstOrInit
As a query condition .The process
When FirstOrInit When finding the result , Will directly give the results touser
.
If we don't find , He can useAttrs
CalledGuanYu
Structure , And assign value touser
The original table
mysql> select * from users;
+----+----------+------+--------------------+---------+
| id | name | age | email | company |
+----+----------+------+--------------------+---------+
| 1 | LiuBei | 28 | liubei@xishu.com | shu |
| 2 | GuanYu | 22 | guanyu@xishu.com | shu |
| 3 | ZhangFei | 18 | zhangfei@xishu.com | shu |
+----+----------+------+--------------------+---------+
3 rows in set (0.00 sec)
- Code
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
GuanYu := User{
ID: 3,
Name: "GuanYu",
Age: 22,
Email: "[email protected]",
Company: "shu",
}
var user User
db.Attrs(GuanYu).FirstOrInit(&user, User{
Name: "GuanYu"})
fmt.Println(user)
}
- Output
Because I found Guan Yu , Then the information of Guan Yu is output
OK
{
2 22 GuanYu [email protected] shu}
- If you don't find , Then you should enter the structure
GuanYu
As defined inWu Sheng
Information
OK
{
0 99 WuSheng [email protected].com shen}
1.3 Assign( Assign the parameter to whether it is found or not struct)
1.3.1 Instructions
effect
Assign
Written inFirstOrInit
front , No matterFirstOrInit
Whether the data is found , Will receiveAttrs
Parameter data ofUse
Define a structure asAssign
Parameters of , CoverFirstOrInit
Some data foundExamples
db.Where(xiShu{
Name: "LiuBei"}).Assign(xiShu{
Age: 35}).FirstOrInit(&user)
1.3.2 Example
- Code
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
GuanYu := User{
Name: "WuSheng",
Company: "shen",
}
var user User
db.Assign(GuanYu).FirstOrInit(&user, User{
Name: "GuanYu"})
fmt.Println(user)
}
- Check the output of the result
OK
{
2 22 WuSheng [email protected].com shen}
- The output of the result cannot be found
OK
{
0 0 WuSheng shen}
2. FirstOrCreate
2.1 Basic use
2.1.1 Instructions
2.2.2 Example
- Code
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var user User
db.FirstOrCreate(&user, User{
Name: "ZhaoYun"})
fmt.Println(user)
}
- Undetected output
OK
{
31 0 ZhaoYun }
- No data found , A record will still be added to the table
This data only receives query conditions
mysql> select * from users;
+----+----------+------+--------------------+---------+
| id | name | age | email | company |
+----+----------+------+--------------------+---------+
| 1 | LiuBei | 28 | liubei@xishu.com | shu |
| 2 | GuanYu | 22 | guanyu@xishu.com | shu |
| 3 | ZhangFei | 18 | zhangfei@xishu.com | shu |
| 31 | ZhaoYun | 0 | | |
+----+----------+------+--------------------+---------+
4 rows in set (0.00 sec)
- Check the output of the result
The result will be assigned to the received structure , No data will be added to the table .
OK
{
31 18 ZhaoYun [email protected].com shu}
2.2 Attrs
- Use
andFirstOrInit
The method in is the same . Not found effective - Examples
db.Attrs(ZhaoYun).FirstOrCreate(&user, User{
Name: "ZhaoYun"})
2.3 Assign
- Use
andFirstOrInit
The method in is the same . Whether it is found or not covers the data in the table - Examples
db.Assign(ZhaoYun).FirstOrCreate(&user, User{
Name: "ZhaoYun"})
边栏推荐
- Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
- 2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
- Day11 - my page, user information acquisition, modification and channel interface
- 2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers
- Gym welcomes the first complete environmental document, which makes it easier to get started with intensive learning!
- Global and Chinese market of electrolyte analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese markets for medical temperature sensors 2022-2028: Research Report on technology, participants, trends, market size and share
- 2.5 conversion of different data types (2)
- Vscode reports an error according to the go plug-in go get connectex: a connection attempt failed because the connected party did not pro
- Global and Chinese market of liquid antifreeze 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
2.7 format output of values
Make a simple text logo with DW
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
2022-06-27 advanced network engineering (XII) IS-IS overhead type, overhead calculation, LSP processing mechanism, route revocation, route penetration
FPGA 学习笔记:Vivado 2019.1 工程创建
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
Bright purple crystal meso tetra (4-aminophenyl) porphyrin tapp/tapppt/tappco/tappcd/tappzn/tapppd/tappcu/tappni/tappfe/tappmn metal complex - supplied by Qiyue
Point cloud data denoising
Exercises of function recursion
Gym welcomes the first complete environmental document, which makes it easier to get started with intensive learning!
随机推荐
10 smart contract developer tools that miss and lose
Xctf attack and defense world crypto master advanced area olddriver
Bool blind note - score query
2. Template syntax
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
Print linked list from end to end
2022-06-27 网工进阶(十二)IS-IS-开销类型、开销计算、LSP的处理机制、路由撤销、路由渗透
Part 28 supplement (XXVIII) busyindicator (waiting for elements)
IP address is such an important knowledge that it's useless to listen to a younger student?
IPv6 experiment
Titles can only be retrieved in PHP via curl - header only retrieval in PHP via curl
Commands related to files and directories
BOC protected tryptophan zinc porphyrin (Zn · TAPP Trp BOC) / copper porphyrin (Cu · TAPP Trp BOC) / cobalt porphyrin (cobalt · TAPP Trp BOC) / iron porphyrin (Fe · TAPP Trp BOC) / Qiyue supply
2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
Derivation of decision tree theory
Camera calibration (I): robot hand eye calibration
kubernetes集群搭建efk日志收集平台
Class loading process