当前位置:网站首页>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"})
边栏推荐
- [Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University
- unittest框架基本使用
- Global and Chinese market of liquid antifreeze 2022-2028: Research Report on technology, participants, trends, market size and share
- Gym welcomes the first complete environmental document, which makes it easier to get started with intensive learning!
- 2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers
- Parental delegation mechanism
- 2.6 formula calculation
- Test changes in Devops mode -- learning and thinking
- Phpstudy set LAN access
- Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
猜你喜欢
Popularize the basics of IP routing
2022-06-25 advanced network engineering (XI) IS-IS synchronization process of three tables (neighbor table, routing table, link state database table), LSP, cSNP, psnp, LSP
Professional interpretation | how to become an SQL developer
Part 28 supplement (XXVIII) busyindicator (waiting for elements)
BOC protected alanine porphyrin compound TAPP ala BOC BOC BOC protected phenylalanine porphyrin compound TAPP Phe BOC Qi Yue supply
2.6 formula calculation
Gym welcomes the first complete environmental document, which makes it easier to get started with intensive learning!
Kubernetes cluster builds efk log collection platform
2.4 conversion of different data types
Chapter 1: find the algebraic sum of odd factors, find the same decimal sum s (D, n), simplify the same code decimal sum s (D, n), expand the same code decimal sum s (D, n)
随机推荐
HCIA-USG Security Policy
2022-06-25 advanced network engineering (XI) IS-IS synchronization process of three tables (neighbor table, routing table, link state database table), LSP, cSNP, psnp, LSP
BOC protected alanine porphyrin compound TAPP ala BOC BOC BOC protected phenylalanine porphyrin compound TAPP Phe BOC Qi Yue supply
Utilisation de base du cadre unitest
Network security Kali penetration learning how to get started with web penetration how to scan based on nmap
QT tutorial: signal and slot mechanism
Win10 share you don't have permission
Derivation of decision tree theory
Machine learning support vector machine SVM
Use of CMD command
Rad+xray vulnerability scanning tool
Global and Chinese market of high temperature Silver sintering paste 2022-2028: Research Report on technology, participants, trends, market size and share
AcWing 1460. Where am i?
Basic command of IP address configuration ---ip V4
1.4 learn more about functions
The simplicity of laravel
Bright purple crystal meso tetra (4-aminophenyl) porphyrin tapp/tapppt/tappco/tappcd/tappzn/tapppd/tappcu/tappni/tappfe/tappmn metal complex - supplied by Qiyue
Micro service knowledge sorting - three pieces of micro Service Technology
Unittest framework is basically used
Professional interpretation | how to become an SQL developer