Article Directory
1 chorm
xorm is a Go language ORM library, its documentation: http://xorm.topgoer.com/
2 Basic operation CRUD
2.1 check
2.1.1 ID query
- ID: The parameter receives the value of the primary key field
var user User
engine.Id(1).Get(&user)
- sql statement:
select * from user where id = 1
2.1.2 Where query
- Where: SQL-like statement
engine.Where('user_name = ? and pwd = ?', 'davie', '123').Get(&admin)
// 或
engine.Where('user_name = ?','davie').Where('pwd = ?','123').Get(&admin)
- sql statement:
select * from user where user_name = 'davie' and pwd = '123'
2.1.3 Get check list
result := User
err := engine.Where("student_name = ?", OrgName).Get(&result)
2.1.4 Find multiple entries
results := make([]User, 0)
err := engine.Where("student_name = ?", OrgName).Find(&results)
2.1.5 Count
engine.Count(&user)
2.2 increase
2.1.1 Single increase
var user
engine.Insert(&user)
2.1.2 Batch increase
// user为切片
user := []User{user1,user2}
engine.Insert(&user)
2.3 change
user:= students.table1{
age: 12,
}
engine.Where("name = ?","new").Update(&user)
2.4 delete
engine.Where("name = ?","new").Delete(&user)
3 affairs
When there is a need to operate data in batches, transactions are required. In xorm, transaction operations are associated with Session. There are three steps in total, namely: create a session object, begin the execution of the Begin transaction, and commit the transaction. The middle is the specific database operation.
- Transaction code:
// 创建事务
session := engine.NewSession()
defer session.Close()
// 事务开始
err := session.Begin()
if err != nil {
return err
}
// 事务相关操作
_, err := dao.Students.DeleteStudents(session, Name)
if err != nil {
// 事务回滚
session.Rollback()
return err
}
事务提交
err = session.Commit()
if err != nil{
return err
}
- Test function, delete data by specified Name:
func (*dStudents) DeleteStudents(session *xorm.Session, Name string) (int64, error) {
result := students.table1{
DeletedAt: time.Now().UnixMilli(),
}
return session.Table("table1").Where("student_name = ?", OrgName).Where("deleted_at = ?", 0).Update(&result)
}
4 Reference
Go language learning tutorial: basic operation and advanced operation of xorm table:
http://www.taodudu.cc/news/show-732070.html?action=onClick
Go-MySQL(四)XORM:
https://blog.csdn.net/weixin_41922289/article/details/116282272