当前位置:网站首页>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;
边栏推荐
- Leetcode-6109: number of people who know secrets
- 1039 Course List for Student
- 传统数据库逐渐“难适应”,云原生数据库脱颖而出
- 1041 Be Unique
- Liunx starts redis
- Leetcode backtracking method
- [practical skills] technical management of managers with non-technical background
- 2022年贵州省职业院校技能大赛中职组网络安全赛项规程
- [rust notes] 17 concurrent (Part 1)
- Records of some tools 2022
猜你喜欢

Spark中groupByKey() 和 reduceByKey() 和combineByKey()

Sqlmap tutorial (1)

Matrixdb V4.5.0 was launched with a new mars2 storage engine!

LVS简介【暂未完成(半成品)】

leetcode-6110:网格图中递增路径的数目

Leetcode-6108: decrypt messages

QQ电脑版取消转义符输入表情

MySQL advanced part 2: optimizing SQL steps

Groupbykey() and reducebykey() and combinebykey() in spark

Appium automation test foundation - Summary of appium test environment construction
随机推荐
WordPress switches the page, and the domain name changes back to the IP address
Leetcode-6110: number of incremental paths in the grid graph
SPI details
Leetcode stack related
Daily question 2006 Number of pairs whose absolute value of difference is k
One question per day 2047 Number of valid words in the sentence
Leetcode-9: palindromes
2022年貴州省職業院校技能大賽中職組網絡安全賽項規程
【Rust 笔记】17-并发(上)
[rust notes] 13 iterator (Part 2)
On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech
1039 Course List for Student
QT判断界面当前点击的按钮和当前鼠标坐标
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
927. 三等分 模拟
Golang uses context gracefully
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
[cloud native] record of feign custom configuration of microservices
“磐云杯”中职网络安全技能大赛A模块新题
Appium automation test foundation - Summary of appium test environment construction