User表
我们回顾下上篇文章,写的User模型
type Users struct {
Id int `pk orm:"column(id)"`
Name string ` orm:"column(name);size(15)"`
Pwd string ` orm:"column(pwd);size(20)"`
Age int ` orm:"column(age)"`
Sex string ` orm:"column(sex);size(2)"`
}
增查改删,都将对下表进行操作。
增加数据 Insert
func (this *InsertController) Post() {
/*
Name :="admin"
Pwd :="12346"
Sex :="男"
Age :=20
*/
Name :=this.GetString("Name")
Pwd :=this.GetString("Pwd")
Sex :=this.GetString("Sex")
Age,err:=this.GetInt("Age")
if err!=nil {
this.Ctx.WriteString("非法年龄字段")
return
}
user:=models.Users{Name:Name,Pwd:Pwd,Sex:Sex,Age:Age}
insOrm:=orm.NewOrm()
n,err:=insOrm.Insert(&user)
if err==nil&&n>0 {
this.Ctx.WriteString("数据插入成功")
}else{
this.Ctx.WriteString("数据插入失败")
}
}
查询数据 Read
func (this *QueryController)Get() {
id,err:=this.GetInt("id")
if err!=nil {
this.Ctx.WriteString("id异常")
return
}
user:= models.Users{Id:id} //获取指定id的数据
orm:=orm.NewOrm()
err=orm.Read(&user) //读取数据
if err==nil {
this.Ctx.WriteString("id="+strconv.Itoa(user.Id)+"\nname="+user.Name+"\nsex="+user.Sex)
}else{
this.Ctx.WriteString("查询失败")
}
}
修改数据 Update
更新全部字段
func (this *UpdataController)Get() {
Id,err:=this.GetInt("Id")
if err!=nil {
this.Ctx.WriteString("id异常")
return
}
Name :=this.GetString("Name")
Pwd :=this.GetString("Pwd")
Sex :=this.GetString("Sex")
Age,err:=this.GetInt("Age")
if err!=nil {
this.Ctx.WriteString("非法年龄字段")
return
}
user:= models.Users{Id:Id,Name:Name,Pwd:Pwd,Age:Age,Sex:Sex}
orm:=orm.NewOrm()
n,err:=orm.Update(&user)
if n>0&&err==nil{
this.Ctx.WriteString("更新成功")
}else{
this.Ctx.WriteString("更新失败")
}
}
删除数据
func (this *DeleteController) Get() {
id,err:=this.GetInt("id")
if err!=nil {
this.Ctx.WriteString("删除失败")
return
}
user:= models.Users{Id:id}
orm:=orm.NewOrm()
n,err:=orm.Delete(&user)
if n>0&&err==nil {
this.Ctx.WriteString("删除成功")
}else{
this.Ctx.WriteString("删除失败")
}
}
作者:Clown95
来源:CSDN
原文:https://blog.csdn.net/yang731227/article/details/82502313
版权声明:本文为博主原创文章,转载请附上博文链接!