当前位置:网站首页>11-gorm-v2-03-basic query
11-gorm-v2-03-basic query
2022-07-05 06:15:00 【Operation and maintenance xuandegong】
List of articles
1. A simple example
Start with an example
- The table below
mysql> select * from xi_shu;
+----+------------+------+
| id | name | age |
+----+------------+------+
| 1 | LiuBei | 28 |
| 2 | GuanYu | 22 |
| 3 | ZhangFei | 20 |
+----+------------+------+
6 rows in set (0.00 sec)
- Code
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()
var users []User
db.Find(&users)
fmt.Println(users)
}
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
}
- The output is as follows
OK
[{
1 28 LiuBei} {
2 22 GuanYu} {
3 20 ZhangFei}]
2. The basic query
2.1 Get the first record , Sort by primary key
db.First(&user)
SELECT * FROM users ORDER BY id LIMIT 1;
2.2 Get a record , Do not specify sorting
db.Take(&user)
SELECT * FROM users LIMIT 1;
2.3 Get the last record , Sort by primary key
db.Last(&user)
SELECT * FROM users ORDER BY id DESC LIMIT 1;
2.4 Get all the records
db.Find(&users)
SELECT * FROM users;
2.5 Query through the primary key ( Only applicable if the primary key is numeric )
db.First(&user, 2)
SELECT * FROM users WHERE id = 10;
2.6 Query the specified field
db.Select("name,age").Find(&users)
- Example
func main() {
db,_ := connect()
defer db.Close()
var users []xiShu
db.Select("name,age").Find(&users)
fmt.Println(user)
}
- Example ( Using slices )
db.Select([]string{
"name", "age"}).Find(&users)
3. where
3.1 Native sql
3.1.1 Easy to use
- grammar
db.Where("name = ?", "LiuBei").First(&users)
SELECT * FROM users WHERE name = 'LiuBei' limit 1;
- Example 1
"1. A simple example " in main The function is replaced as follows :
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var users []User
db.Where("name = ?", "LiuBei").First(&users)
fmt.Println(users)
db.Where("name = ?", "GuanYu").First(&users)
fmt.Println(users)
}
Query results :
OK
&[{
1 LiuBei 28}]
&[{
2 GuanYu 22}]
- Example 2
If continuous query uses structure to receive data
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var user User
db.Where("name = ?", "LiuBei").First(&user)
fmt.Println(user)
db.Where("name = ?", "GuanYu").First(&user)
fmt.Println(user)
}
Output is
OK
{
1 28 LiuBei}
2022/02/11 23:54:54 /data/goproject/src/crow-gorm/main.go:29 record not found
[0.796ms] [rows:0] SELECT * FROM `users` WHERE name = 'GuanYu' AND `users`.`id` = 1 ORDER BY `users`.`id` LIMIT 1
{
1 28 LiuBei}
Error reporting is visible "WHERE name = ‘GuanYu’ AND `users`.`id` = 1 ", Explain that the results of the first query will be brought to the second query
Tried it on , If the structure data is cleared before the second query , You can query for the second time
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var user User
db.Where("name = ?", "LiuBei").First(&user)
fmt.Println(user)
user = User{
} // eliminate user
db.Where("name = ?", "GuanYu").First(&user)
fmt.Println(user)
}
3.1.2 <> ( Not for )
db.Where("name <> ?", "LiuBei").Find(&users)
3.1.3 IN
db.Where("name in (?)", []string{
"CaoCao","LiuBei","SunQuan"}).Find(&users)
3.1.4 LIKE
db.Where("name LIKE ?", "%Liu%").Find(&users)
3.1.5 AND
db.Where("name = ? AND Age > ? ", "LiuBei",20).Find(&users)
3.1.6 BETWEEN
db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
3.1.7 Time
db.Where("updated_at < ?", currentTime).Find(&users)
3.2 adopt go Object query for
3.2.1 adopt Struct Inquire about
- grammar
db.Where(STRUCT_NAME).First(&users)
- Example
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
user := User {
Name: "GuanYu",
Age: 22,
}
db.Where(user).First(&user)
fmt.Println(user)
}
3.2.2 adopt Map Inquire about
db.Where(map[string]interface{
}{
"name": "GuanYu", "age": 22}).Find(&users)
3.2.3 Pay attention to problems
- The value is
0、''、falseThis field will not be used to build query conditions
func main() {
db,_ := connect()
defer db.Close()
var users []User
result := db.Where(map[string]interface{
}{
"name": 0, "age": 20}).Find(&users)
fmt.Println(users)
}
result
OK
[{
3 ZhangFei 20} {
5 ZhuGeLiang 20} {
6 MaChao 20}]
so ,name The value of is 0,ID Empty will not , Do not write sql sentence .
4. Not
and WHERE similar , Don't start the story
- Get the first record after filtering , Sort by primary key
db.Not("name", "LiuBei").First(&user)
SELECT * FROM users WHERE name <> "LiuBei" LIMIT 1;
- Using arrays / Slice filter
db.Not("name", []string{
"CaoCao", "LiuBei","SunQuan"}).Find(&users)
SELECT * FROM users WHERE name NOT IN ("CaoCao", "LiuBei","SunQuan");
- Not in primary key slice in
db.Not([]int64{
1,2,3}).First(&user)
SELECT * FROM users WHERE id NOT IN (1,2,3);
Example
func main() {
db,_ := connect()
defer db.Close()
var users []User
result := db.Not([]int64{
1,2,3}).Find(&users)
fmt.Println(users)
}
result
[{
4 ZhaoYun 18} {
5 ZhuGeLiang 20} {
6 MaChao 20}]
As you can see above ,ID yes 1.2.3 That's filtered
- Native SQL
db.Not("name = ?", "LiuBei").First(&user)
SELECT * FROM users WHERE NOT(name = "LiuBei");
- Struct/Map
db.Not(map[string]interface{
}{
"name": "LiuBei", "age": 20}).Find(&users)
SELECT * FROM users WHERE name <> "LiuBei";
5. Or
Connect two conditions , The two sides can be written in different ways , If one side is primitive sql On one side is the structure :
db.Where("name = ?", "LiuBei").Or(xiShu{
Name: "GuanYu"}).Find(&users)
6. Intra line condition query
- Non numeric primary key query
db.First(&user, 2)
SELECT * FROM users WHERE id = 23 LIMIT 1;
Example
func main() {
db,_ := connect()
defer db.Close()
var users []User
result := db.First(&users, 2)
fmt.Println(users)
}
- Primary key query ( Numbers / Non digital )
db.First(&user, "id = ?", "xxxx")
SELECT * FROM users WHERE id = 'xxxxx' LIMIT 1;
- Native SQL
db.Find(&users, "name = ?", "LiuBei")
SELECT * FROM users WHERE name = "LiuBei";
db.Find(&users, "name <> ? AND age > ?", "LiuBei", 20)
SELECT * FROM users WHERE name <> "LiuBei" AND age > 20;
- Struct
db.Find(&users, User{
Age: 20})
SELECT * FROM users WHERE age = 20;
- Map
db.Find(&users, map[string]interface{
}{
"age": 20})
SELECT * FROM users WHERE age = 20;
边栏推荐
- Multi screen computer screenshots will cut off multiple screens, not only the current screen
- QQ电脑版取消转义符输入表情
- Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
- 【Rust 笔记】15-字符串与文本(下)
- Basic explanation of typescript
- 1996. number of weak characters in the game
- js快速将json数据转换为url参数
- [rust notes] 15 string and text (Part 1)
- TypeScript 基础讲解
- [rust notes] 13 iterator (Part 2)
猜你喜欢
![[cloud native] record of feign custom configuration of microservices](/img/39/05cf7673155954c90e75a8a2eecd96.jpg)
[cloud native] record of feign custom configuration of microservices

1.13 - RISC/CISC

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

MySQL advanced part 1: stored procedures and functions

SPI 详解

Dynamic planning solution ideas and summary (30000 words)

1.13 - RISC/CISC

Error ora-28547 or ora-03135 when Navicat connects to Oracle Database

Appium foundation - use the first demo of appium

LeetCode 0108. Convert an ordered array into a binary search tree - the median of the array is the root, and the left and right of the median are the left and right subtrees respectively
随机推荐
The sum of the unique elements of the daily question
Regulations for network security events of vocational group in 2022 Guizhou Vocational College skill competition
leetcode-31:下一个排列
【Rust 笔记】13-迭代器(下)
一些工具的记录2022
1.14 - assembly line
Leetcode-6111: spiral matrix IV
Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
对for(var i = 0;i < 5;i++) {setTimeout(() => console.log(i),1000)}的深入分析
1039 Course List for Student
One question per day 1020 Number of enclaves
Leetcode-31: next spread
7. Processing the input of multidimensional features
New title of module a of "PanYun Cup" secondary vocational network security skills competition
wordpress切换页面,域名变回了IP地址
QQ电脑版取消转义符输入表情
1996. number of weak characters in the game
“磐云杯”中职网络安全技能大赛A模块新题
R language [import and export of dataset]
Daily question 1984 Minimum difference in student scores