Beego -- ORM
安装
go get github.com/astaxie/beego/orm
建表
加在models包
beego 的main文件中
package models
import (
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql" // mysql驱动
)
type User struct {
Id int
Name string
Password string
CreateTime time.Time
}
// 加载这个文件时,自动执行init函数
func init() {
// 设置链接数据库链接的基本信息
orm.RegisterDataBase("default", "mysql",
"xiaoma:My101523@tcp(rm-2vcs07lhst811719q1o.mysql.cn-chengdu.rds.aliyuncs.com:3306)/test?charset=utf8")
// 创建表,可以创建多个orm.RegisterModel(new(User),new(UserInfo))
//orm.RegisterModel(new(User))
// 指定前缀,表名为"firstAPI_结构体名",全部转成小写
orm.RegisterModelWithPrefix("firstAPI_",new(User))
// 生成表,false 不强制更新,默认false, true sql命令是否可见
orm.RunSyncdb("default", false, true)
}
如果报错没有驱动
go mod tidy // 安装新的依赖
单表插入
// 向数据库的表中插入一条数据
o := orm.NewOrm() // ORM对象
// 创建一个结构体对象
user := models.User{
Name: "xiaoming",
Password: "123",
}
// 将需要结构体插入到表中
num,err := o.Insert(&user)
if err != nil{
fmt.Println("插入失败",err)
return
}else{
fmt.Println("插入成功",num)
}
建表的字段属性限制
int类型
Id int `orm:"pk;auto"` // 主键并自增
Gender int `orm:"default(1)"` // 默认值为1
时间类型
CreateTime time.Time `orm:"auto_now_add;type(datatime)"` // auto_now_add 第一次保存时才设置时间
ChangeTime time.Time `orm:"auto_now;type(date)"` // date类型时间,auto_now表示每次model保存时都会对时间自动更新
字符串类型
Name string `orm:"size(10);null"` // 最大长度,null表示可以为空,默认所有字段不允许为空
浮点数类型
Money float `orm:"digits(12);decimals(4)"` // 总长度为12,小数部分为4
一对一关系创建
一对多关系创建
多对多关系创建
单表查询
// 查询
o := orm.NewOrm()
user := models.User{}
// 指定查询条件为ID = 1
// user.Id = 1
//err := o.Read(&user) // 指定ID查询时,不用加col参数
// 指定查询条件为Name = "xiaoming"
user.Name = "xiaoming"
err := o.Read(&user,"Name") // 其他字段查询,需指定查询字段
if err != nil{
fmt.Println("查询失败")
return
}
fmt.Println(user)
articles := []models.Article
_,err := o.QueryTable("表名").All(&articles)
单表更新
// 更新
o := orm.NewOrm()
user := models.User{}
// 1. 找到需要更新的数据
user.Name = "xiaoming"
err := o.Read(&user,"Name")
if err != nil{
fmt.Println("查询失败")
return
}
// 2. 给数据重新赋值
user.Name = "xiaobai"
// 3. 更新对象
_,err = o.Update(&user,"Name") // 其他字段查询,需指定查询字段
if err != nil{
fmt.Println("更新失败")
return
}
fmt.Println(user)
单表删除
// 删除
o := orm.NewOrm()
user := models.User{}
// 1. 找到需要删除的数据
user.Name = "xiaobai"
err := o.Read(&user,"Name")
if err != nil{
fmt.Println("查询失败")
return
}
// 2. 指定删除哪一条
_,err = o.Delete(&user,"Name") // 其他字段查询,需指定查询字段
if err != nil{
fmt.Println("删除失败")
return
}
fmt.Println(user)
python防脱发技巧

浙公网安备 33010602011771号