当前位置:网站首页>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"})
边栏推荐
- 4. Data splitting of Flink real-time project
- 2022-06-28 advanced network engineering (XIII) IS-IS route filtering, route summary, authentication, factors affecting the establishment of Isis neighbor relations, other commands and characteristics
- What is the difference between a kill process and a close process- What are the differences between kill process and close process?
- Derivation of decision tree theory
- 10 smart contract developer tools that miss and lose
- 2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
- Bool blind note - score query
- Global and Chinese market of liquid antifreeze 2022-2028: Research Report on technology, participants, trends, market size and share
- Phpstudy set LAN access
- App compliance
猜你喜欢
The 29th day of force deduction (DP topic)
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
Chapter 20: y= sin (x) /x, rambling coordinate system calculation, y= sin (x) /x with profile graphics, Olympic rings, ball rolling and bouncing, water display, rectangular optimization cutting, R que
The 15 year old interviewer will teach you four unique skills that you must pass the interview
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
MPLS configuration
CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
IP address is such an important knowledge that it's useless to listen to a younger student?
Upgrade PIP and install Libraries
Network security Kali penetration learning how to get started with web penetration how to scan based on nmap
随机推荐
Use of aggregate functions
Point cloud data denoising
Promethus
FAQs for datawhale learning!
Xctf attack and defense world crypto advanced area best_ rsa
Native table - scroll - merge function
AI enhanced safety monitoring project [with detailed code]
Exercises of function recursion
2022-06-30 網工進階(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
First knowledge of database
Plan for the first half of 2022 -- pass the PMP Exam
Part 27 supplement (27) buttons of QML basic elements
kubernetes集群搭建efk日志收集平台
1.4 learn more about functions
BOC protected tryptophan porphyrin compound (TAPP Trp BOC) Pink Solid 162.8mg supply - Qiyue supply
4. Data splitting of Flink real-time project
BOC protected alanine porphyrin compound TAPP ala BOC BOC BOC protected phenylalanine porphyrin compound TAPP Phe BOC Qi Yue supply
原生表格-滚动-合并功能
Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
Part 28 supplement (XXVIII) busyindicator (waiting for elements)