当前位置:网站首页>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;
边栏推荐
- 传统数据库逐渐“难适应”,云原生数据库脱颖而出
- 1040 Longest Symmetric String
- MySQL advanced part 1: triggers
- MySQL advanced part 1: stored procedures and functions
- 【Rust 笔记】17-并发(上)
- 一些工具的记录2022
- Appium自动化测试基础 — Appium测试环境搭建总结
- How to adjust bugs in general projects ----- take you through the whole process by hand
- Records of some tools 2022
- SPI 详解
猜你喜欢
Introduction to LVS [unfinished (semi-finished products)]
快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
MIT-6874-Deep Learning in the Life Sciences Week 7
Data visualization chart summary (II)
LaMDA 不可能觉醒吗?
SQLMAP使用教程(二)实战技巧一
MySQL advanced part 1: index
1.15 - input and output system
1.15 - 输入输出系统
LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树
随机推荐
leetcode-9:回文数
Basic explanation of typescript
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
[rust notes] 14 set (Part 1)
Shutter web hardware keyboard monitoring
Leetcode-3: Longest substring without repeated characters
QT判断界面当前点击的按钮和当前鼠标坐标
1040 Longest Symmetric String
SQLMAP使用教程(一)
liunx启动redis
QQ电脑版取消转义符输入表情
1.14 - assembly line
【Rust 笔记】13-迭代器(中)
In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
Leetcode-6109: number of people who know secrets
Daily question 1189 Maximum number of "balloons"
[rust notes] 14 set (Part 2)
leetcode-1200:最小绝对差
Leetcode-6110: number of incremental paths in the grid graph
1.13 - RISC/CISC