创建RawDemo
/*
------------------------------------------------------
使用 Raw SQL 查询,无需使用 ORM 表定义
多数据库,都可直接使用占位符号 ?,自动转换
查询时的参数,支持使用 Model Struct 和 Slice, Array
------------------------------------------------------
*/
type RawDemo struct {
Id int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Mobile string `json:"mobile"`
Age int `json:"age"`
IsDelete int `json:"is_delete"`
Sex int `json:"sex"`
Qq int `json:"qq"`
Status int `json:"status"`
}
QueryRow查询
func GetRawDemoQueryRowById(id int) RawDemo {
var rawDemo RawDemo
err := orm.NewOrm().Raw("SELECT * FROM demo WHERE id = ?", id).QueryRow(&rawDemo)
if err == nil {
//
}
return rawDemo
}
image.png
QueryRows查询
func GetRawDemoQueryRowsByStatus(status int) ([]RawDemo, int64) {
var rawDemo []RawDemo
num, err := orm.NewOrm().Raw("SELECT * FROM demo WHERE status = ?", status).QueryRows(&rawDemo)
if err == nil {
//
}
return rawDemo, num
}
image.png
Values查询
func GetRawDemoByStatus(status int) ([]orm.Params, int64) {
var maps []orm.Params
num, err := orm.NewOrm().Raw("SELECT * FROM demo WHERE status = ?", status).Values(&maps)
if err == nil {
//
}
return maps, num
}
image.png
更新数据
func UpdateRawDemo(id int) int64 {
res, err := orm.NewOrm().Raw("UPDATE demo SET `name` = '孙权' WHERE id = ?", id).Exec()
if err == nil {
num, _ := res.RowsAffected()
if num > 0 {
return num
}
}
return 0
}
添加数据
func InsertRawDemo() int64 {
/*
参数传递1
res, err := orm.NewOrm().Raw("INSERT INTO demo(`name`, `email`, `mobile`, `age`, `is_delete`, `sex`, `qq`, `status`) " +
"VALUES(?, ?, ?, ?, ?, ?, ?, ?)", "孙权", "hainan@126.com", "15811111111", 20, 1, 1, 333999999, 1).Exec()
*/
// 参数传递2
values := []string{"孙权", "hainan@126.com", "15822222222", "20", "1", "1", "333888888", "1"}
res, err := orm.NewOrm().Raw("INSERT INTO demo(`name`, `email`, `mobile`, `age`, `is_delete`, `sex`, `qq`, `status`) " +
"VALUES(?, ?, ?, ?, ?, ?, ?, ?)", values).Exec()
if err == nil {
num, _ := res.LastInsertId()
if num > 0 {
return num
}
}
return 0
}
删除数据
func DeleteRawDemoById(id int) int64 {
res, err := orm.NewOrm().Raw("DELETE FROM demo WHERE id = ?", id).Exec()
if err == nil {
num, _ := res.RowsAffected()
if num > 0 {
return num
}
}
return 0
}
网友评论