go学习笔记:gorm基本使用
关于gorm的使用,官网非常详细推荐大家有时间仔细看 https://gorm.io/zh_CN/docs/conventions.html, 我这里只是演示日常的使用增删改查:
创建数据:
新建一个gormdemo的数据库,然后执行下面的sql语句,就会建立一个animals的表,里面还有一些测试数据
CREATE TABLE `animals` ( `id` BIGINT(20) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) DEFAULT 'galeone', `age` INT(10) UNSIGNED DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MYISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of animals -- ---------------------------- INSERT INTO `animals` VALUES ('1', 'demo-test', '20'); INSERT INTO `animals` VALUES ('2', 'galeone', '30'); INSERT INTO `animals` VALUES ('3', 'demotest', '30'); INSERT INTO `animals` VALUES ('4', 'jim', '90'); INSERT INTO `animals` VALUES ('5', 'jimmy', '10'); INSERT INTO `animals` VALUES ('6', 'jim', '23'); INSERT INTO `animals` VALUES ('7', 'test3', '27');
我们常规就是插入,修改,删除,还有事务以及FOR UPDATE排它锁:
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type Animal struct {
ID int64
Name string
Age int64
}
func main() {
db, err := gorm.Open("mysql", "root:root@(localhost)/gormdemo?charset=utf8&parseTime=true&loc=Local")
if err != nil {
fmt.Println("connect db error: ", err)
}
defer db.Close()
init_data(db)
query_test(db)
err=update_test(db)
if err!=nil{
fmt.Println(err)
}
err=delet_test(db)
if err!=nil{
fmt.Println(err)
}
err=trans_test(db)
if err!=nil{
fmt.Println(err)
}
}
func init_data(db *gorm.DB) {
sql:=`DROP TABLE IF EXISTS animals ;`
db.Exec(sql)
sql=`
CREATE TABLE animals (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255) DEFAULT 'galeone',
age INT(10) UNSIGNED DEFAULT '0',
PRIMARY KEY (id)
) ENGINE=INNODB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;`
db.Exec(sql)
sql=`
INSERT INTO animals SELECT '1', 'demo-test', '20'
UNION ALL SELECT '2', 'galeone', '30'
UNION ALL SELECT '3', 'demotest', '30'
UNION ALL SELECT '4', 'jim', '90'
UNION ALL SELECT'5', 'jimmy', '10'
UNION ALL SELECT '6', 'jim', '23'
UNION ALL SELECT '7', 'test3', '27'
`
db.Exec(sql)
}
func create_test(db * gorm.DB)(error) {
animal := Animal{Name: "demo-test", Age: 20}
db.Create(&animal)
return nil
}
func query_test(db *gorm.DB)(error) {
//根据主键查询第一条记录
var animal Animal
db.First(&animal)
fmt.Println(animal)
//根据主键查询最后一条记录
var animal2 Animal
db.Last(&animal2)
fmt.Println(animal2)
//指定某条记录(仅当主键为整型时可用)
var animal3 Animal
db.First(&animal3, 2)
fmt.Println(animal3)
//where条件
//符合条件的第一条记录
var animal4 Animal
db.Where("name = ?", "demo-test").First(&animal4)
fmt.Println("where : ", animal4, animal4.ID, animal4.Name, animal4.Age)
//符合条件的所有记录
var animals5 []Animal
db.Where("name = ?", "galeone").Find(&animals5)
fmt.Println(animals5)
for k, v := range animals5 {
fmt.Println("k:", k, "ID:", v.ID, "Name:", v.Name, "Age:", v.Age)
}
//IN
var animals6 []Animal
db.Where("name IN (?)", []string{"demo-test", "demotest2"}).Find(&animals6)
fmt.Println(animals6)
//LIKE
var animals7 []Animal
db.Where("name like ?", "%jim%").Find(&animals7)
fmt.Println(animals7)
//AND
var animals8 []Animal
db.Where("name = ? AND age >= ?", "jim", "24").Find(&animals8)
fmt.Println(animals8)
//总数
var count int
var animals9 []Animal
db.Where("name = ?", "galeone").Or("name = ?", "jim").Find(&animals9).Count(&count)
fmt.Println(animals9)
fmt.Println(count)
//Scan, 原生查询
var animals10 []Animal
db.Raw("SELECT id, name, age From Animals WHERE name = ? AND age = ? ", "galeone", "30").Scan(&animals10)
fmt.Println("Scan: ", animals10)
//原生查询,select all
var animals11 []Animal
rows, _ := db.Raw("SELECT id,name FROM Animals").Rows()
//注意:上面的 select id,name 后面不能写成 * 代替,不然出来的结果都是默认0值
//像这样结果: ALL: [{0 0} {0 0} {0 0} {0 0} {0 0} {0 0} {0 0}]
//Scan 后面是什么字段,select 后面就紧跟什么字段
for rows.Next() {
var result Animal
rows.Scan(&result.ID, &result.Name)
animals11 = append(animals11, result)
}
fmt.Println("ALL: ", animals11)
//output:ALL: [{1 demo-test 0} {2 galeone 0} {3 demotest2 0} {4 galeone 0} {5 galeone 0} {6 jim 0} {7 jimmy 0}]
//select 查询
var animal12 Animal
db.Select("name,age").Find(&animal12) //只查询name,age字段,相当于select name,age from user
fmt.Println("select: ", animal12)
//map 结构
animals13:=map[int64]Animal{}
var animals14 []Animal
db.Raw("SELECT id, name, age From Animals WHERE id>5").Find(&animals14)
for _,v:= range animals14{
animals13[v.ID]=v
}
fmt.Println(animals13)
return nil
}
func update_test(db *gorm.DB)(err error){
//根据条件更新字段值,
//后面加Debug(),运行时,可以打印出sql
err=db.Debug().Model(&Animal{}).Where("id = ? ", 5).Update("name", "jimupdate").Error
if err!=nil{
return err
}
//UPDATE `animals` SET `name` = 'jimupdate' WHERE (id = 4)
//另外一种写法: 根据条件更新
var animal Animal
animal = Animal{ID: 3}
err=db.Debug().Model(animal).Update("name", "demotest2update").Error
if err!=nil{
return err
}
// db.Debug().Model(&animal).Update("name", "demotest2update") // 这种写法也可以
//UPDATE `animals` SET `name` = 'demotest2update' WHERE `animals`.`id` = 3
/// 多个条件更新
err=db.Model(&Animal{}).Where("id = ? AND age = ?", 4, 90).Update("name", "jimupdate3").Error
if err!=nil{
return err
}
//UPDATE `animals` SET `name` = 'jimupdate2' WHERE (id = 4 AND age = 45)
/// 更新多个值
err=db.Debug().Model(&Animal{}).Where("id = ?", 6).Update(Animal{Name: "jim", Age: 90}).Error
if err!=nil{
return err
}
// UPDATE `animals` SET `age` = 90, `name` = 'jim' WHERE (id = 4)
animal2 := Animal{ID: 7}
err=db.Debug().Model(&animal2).Update(map[string]interface{}{"name": "jimm", "age": 27}).Error
//UPDATE `animals` SET `age` = 100, `name` = 'jimm' WHERE `animals`.`id` = 5
return nil
}
func delet_test(db *gorm.DB)(err error) {
err=db.Debug().Where("id = ?", 7).Delete(&Animal{}).Error
if err!=nil{
return err
}
// DELETE FROM `animals` WHERE (id = 13)
err=db.Debug().Delete(&Animal{}, "id = ? AND age = ?", 6, 90).Error
//DELETE FROM `animals` WHERE (id = 14 AND age = 10)
return err
}
func trans_test(db *gorm.DB)(wrong error) {
tx:=db.Begin()
defer func() {
if err:=recover(); err!=nil{
tx.Rollback()
if val,ok:=err.(error); ok{
wrong=val
}
} else{
err:=tx.Commit().Error
if err !=nil{
tx.Rollback()
wrong=err
}
}
}()
an:= Animal{Name: "gavin", Age: 35}
err:=tx.Create(&an).Error
if err!=nil{
panic(err)
}
err=tx.Exec("UPDATE animals SET age=40 WHERE id=1").Error
if err!=nil{
panic(err)
}
trans_test2(tx)
return nil
}
func trans_test2(db *gorm.DB) {
var animals1 Animal
//err:=db.Set("gorm:query_option", "FOR UPDATE").Table("animals").Select("id, `NAME`,Age").Where("ID=?",2).Find(&animals1).Error
err:=db.Set("gorm:query_option", "FOR UPDATE").First(&animals1,2).Error
if err!=nil{
fmt.Println(err)
panic(err)
}
animals1.Name=animals1.Name +"_ gavin update"
err=db.Set("gorm:query_option", "FOR UPDATE").Table("animals").Where("ID=?",2).Update(&animals1).Error
if err!=nil{
fmt.Println(err)
panic(err)
}
}
windows技术爱好者