当前位置:网站首页>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
、''
、false
This 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;
边栏推荐
- [practical skills] how to do a good job in technical training?
- Quickly use Amazon memorydb and build your own redis memory database
- 1040 Longest Symmetric String
- New title of module a of "PanYun Cup" secondary vocational network security skills competition
- js快速将json数据转换为url参数
- 数据可视化图表总结(一)
- Doing SQL performance optimization is really eye-catching
- Data visualization chart summary (I)
- Leetcode-3: Longest substring without repeated characters
- 1.14 - 流水线
猜你喜欢
liunx启动redis
MySQL advanced part 2: the use of indexes
Wazuh開源主機安全解决方案的簡介與使用體驗
wordpress切换页面,域名变回了IP地址
On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech
Network security skills competition in Secondary Vocational Schools -- a tutorial article on middleware penetration testing in Guangxi regional competition
MySQL advanced part 1: index
Leetcode-6108: decrypt messages
leetcode-6108:解密消息
LeetCode 0107.二叉树的层序遍历II - 另一种方法
随机推荐
884. Uncommon words in two sentences
Leetcode-556: the next larger element III
[practical skills] how to do a good job in technical training?
LVS简介【暂未完成(半成品)】
New title of module a of "PanYun Cup" secondary vocational network security skills competition
Collection: programming related websites and books
Liunx starts redis
Regulations for network security events of vocational group in 2022 Guizhou Vocational College skill competition
How to adjust bugs in general projects ----- take you through the whole process by hand
Leetcode heap correlation
Appium foundation - use the first demo of appium
4. 对象映射 - Mapping.Mapster
Binary search template
Leetcode dynamic programming
A reason that is easy to be ignored when the printer is offline
MySQL advanced part 2: the use of indexes
【Rust 笔记】15-字符串与文本(上)
TypeScript 基础讲解
Leetcode-1200: minimum absolute difference
传统数据库逐渐“难适应”,云原生数据库脱颖而出