当前位置:网站首页>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;
边栏推荐
- [rust notes] 14 set (Part 1)
- 927. Trisection simulation
- SPI details
- Currently clicked button and current mouse coordinates in QT judgment interface
- leetcode-556:下一个更大元素 III
- Leetcode recursion
- 1040 Longest Symmetric String
- Groupbykey() and reducebykey() and combinebykey() in spark
- Introduction and experience of wazuh open source host security solution
- 传统数据库逐渐“难适应”,云原生数据库脱颖而出
猜你喜欢

SPI details

1.13 - RISC/CISC

MySQL advanced part 1: View

1.13 - RISC/CISC

On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech

LeetCode 0107. Sequence traversal of binary tree II - another method

Real time clock (RTC)

Traditional databases are gradually "difficult to adapt", and cloud native databases stand out

Spark中groupByKey() 和 reduceByKey() 和combineByKey()
![Introduction to LVS [unfinished (semi-finished products)]](/img/72/d5a943a8d6d71823dcbd7f23dda35b.png)
Introduction to LVS [unfinished (semi-finished products)]
随机推荐
Leetcode-6108: decrypt messages
Leetcode-6109: number of people who know secrets
1.15 - input and output system
leetcode-6110:网格图中递增路径的数目
Currently clicked button and current mouse coordinates in QT judgment interface
Basic explanation of typescript
【Rust 笔记】17-并发(下)
MySQL advanced part 1: triggers
MySQL advanced part 1: stored procedures and functions
Arduino 控制的 RGB LED 无限镜
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
Daily question 2006 Number of pairs whose absolute value of difference is k
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
MySQL advanced part 2: optimizing SQL steps
Network security skills competition in Secondary Vocational Schools -- a tutorial article on middleware penetration testing in Guangxi regional competition
leetcode-3:无重复字符的最长子串
Daily question 1984 Minimum difference in student scores
Groupbykey() and reducebykey() and combinebykey() in spark
LeetCode 1200. Minimum absolute difference
QQ电脑版取消转义符输入表情