首先需要导入包:
go get github.com/go-xorm/xorm
go get github.com/go-xorm/cmd/xorm
之后为了跑案例,创建了数据库表格
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
)
之后首先明确一点xorm的逆向工程类似于mybatis,都需要依赖于特定模板,而在xorm源码中提供了默认模板,这里我go get的时候发现不存在,所以从git中clone后拷贝到了源码当中,具体什么原因还是需要后面探究
创建了之后,就可以运行对应逆向命令
xorm reverse mysql root:密码@/xorm?charset=utf8 模板位置
就可以生成对应的models文件夹
//增
user := new(User)
user.Username="tyming"
affected,err := engine.Insert(user)
fmt.Println(affected)
//删
user := new(User)
user.Username="tyming"
affected_delete,err := engine.Delete(user)
fmt.Println(affected_delete)
//改
user := new(User)
user.Username="tyming"
affected_update,err := engine.Id(1).Update(user)
fmt.Println(affected_update)
//查
user := new(User)
//result,err := engine.Id(1).Get(user)
result,err := engine.Where("id=?",1).Get(user)
fmt.Println(result)
err := engine.Sync2(new(User)) 以struct同步数据库
affected, err := engine.Exec("update user set age = ? where name = ?", age, name) 执行一个SQL语句
affected, err := engine.Insert(&user1, &user2) 插入一条或者多条记录
has, err := engine.Get(&user) 查询单条记录
has, err := testEngine.Exist(new(RecordExist)) 检测记录是否存在
err := engine.Table("user").Select("user.*, detail.*") Join("INNER", "detail", "detail.user_id = user.id").Where("user.name = ?", name).Limit(10, 0). Find(&users)
查询多条记录
affected, err := engine.ID(1).Update(&user)
Update 更新数据,除非使用Cols,AllCols函数指明,默认只更新非空和非0的字段
affected, err := engine.Where(...).Delete(&user)
删除记录,需要注意,删除必须至少有一个条件,否则会报错。要清空数据库可以用EmptyTable
counts, err := engine.Count(&user)
获取记录条数
agesFloat64, err := engine.Sum(&user, "age")
求和
err := engine.Where(builder.NotIn("a", 1, 2).And(builder.In("b", "c", "d", "e"))).Find(&users)
编辑条件
session := engine.NewSession()
defer session.Close()
// add Begin() before any action
if err := session.Begin(); err != nil {
// if returned then will rollback automatically
return err
}
事务开始
user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
if _, err := session.Insert(&user1); err != nil {
return err
}
user2 := Userinfo{Username: "yyy"}
if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
return err
}
if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
return err
}
// add Commit() after all actions
return session.Commit()
事务结束