You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package gormExample
import "log"
// 原生查询测试
func RawSelect() {
// 结果类型
type Result struct {
ID uint
Subject string
Likes, Views int
}
var rs []Result
// SQL
sql := "SELECT `id`, `subject`, `likes`, `views` FROM `msb_content` WHERE `likes` > ? ORDER BY `likes` DESC LIMIT ?"
// 执行SQL并扫描结果
if err := DB.Raw(sql, 99, 12).Scan(&rs).Error; err != nil {
log.Fatalln(err)
}
// [8.298ms] [rows:12] SELECT `id`, `subject`, `likes`, `views` FROM `msb_content` WHERE `likes` > 99 ORDER BY `likes` DESC LIMIT 12
log.Println(rs)
}
// 执行类的SQL原生
func RawExec() {
// SQL
sql := "UPDATE `msb_content` SET `subject` = CONCAT(`subject`, '-new postfix') WHERE `id` BETWEEN ? AND ?"
// 执行,获取结果
result := DB.Exec(sql, 30, 40)
if result.Error != nil {
log.Fatalln(result.Error)
}
// [13.369ms] [rows:10] UPDATE `msb_content` SET `subject` = CONCAT(`subject`, '-new postfix') WHERE `id` BETWEEN 30 AND 40
log.Println(result.RowsAffected)
}
// sql.Row 或 sql.Rows 类型的结果处理
func RowAndRows() {
// sql
sql := "SELECT `id`, `subject`, `likes`, `views` FROM `msb_content` WHERE `likes` > ? ORDER BY `likes` DESC LIMIT ?"
// 执行获取rows
rows, err := DB.Raw(sql, 99, 12).Rows()
if err != nil {
log.Fatalln(err)
}
// 遍历rows
for rows.Next() {
// 扫描的列独立的变量
//var id uint
//var subject string
//var likes, views int
//rows.Scan(&id, &subject, &likes, &views)
//log.Println(id, subject, likes, views)
// 扫描到整体结构体
type Result struct {
ID uint
Subject string
Likes, Views int
}
var r Result
if err := DB.ScanRows(rows, &r); err != nil {
log.Fatalln(err)
}
log.Println(r)
}
}