Beerus-DB,是Beerus的子项目之一,是一个数据库操作框架,用到了[go-sql-driver/mysql]来做数据库连接与基础操作,在此基础上做了很多扩展,比如:连接池管理,多数据源,事务管理,单表无sql操作,多表以及复杂操作可以自己写sql,sql支持{}占位符,可以用struct作为参数来操作数据库等
文档https://beeruscc.com/beerusdb
示例单表操作根据条件查询单表数据conditions:=make([]*entity.Condition,0)conditions=append(conditions,entity.GetCondition("id>?",10))conditions=append(conditions,entity.GetCondition("and(user_name=?orage>?)","bee",18))conditions=append(conditions,entity.GetCondition("orderbycreate_timedesc",entity.NotWhere))resultMap,err:=operation.GetDBTemplate("Datasourcename").Select("tablename",conditions)根据条件修改单表数据//Conditionssetconditions:=make([]*entity.Condition,0)conditions=append(conditions,entity.GetCondition("id=?",1))//Datasettingstobemodifieddata:=ResultStruct{UserName:"TestNoSqlUpdate"}//Executethemodificationoperationresult,err:=operation.GetDBTemplate("Datasourcename").Update("tablename",dbutil.StructToMapIgnore(&data,data,true),conditions)根据条件删除单表数据//Setdeleteconditionsconditions:=make([]*entity.Condition,0)conditions=append(conditions,entity.GetCondition("id=?",2))//Performadeleteoperation_,err:=operation.GetDBTemplate("Datasourcename").Delete("tablename",conditions)插入一条数据data:=ResultStruct{UserName:"TestNoSqlInsert",UserEmail:"xxxxx@163.com",UpdateTime:"2021-12-0913:50:00",}result,err:=operation.GetDBTemplate("Datasourcename").Insert("tablename",dbutil.StructToMapIgnore(&data,data,true))自定义sql查询
//struct参数res:=ResultStruct{Id:1}//查多条,注:这里需要用到占位符resultMap,err:=operation.GetDBTemplate("Datasourcename").SelectListByMap("select*fromxt_message_boardwhereid<{id}",dbutil.StructToMap(&res,res))//查一条,注:这里需要用到占位符resultMap,err:=operation.GetDBTemplate("Datasourcename").SelectOneByMap("select*fromxt_message_boardwhereid<{id}",dbutil.StructToMap(&res,res))增删改
res:=ResultStruct{Id:1,UserName:"TestUpdateByMap"}//无论是增删改,都是调用ExecByMap函数,将sql和参数传入即可,注:这里需要用到占位符operation.GetDBTemplate("Datasourcename").ExecByMap("updatext_message_boardsetuser_name={user_name}whereid={id}",dbutil.StructToMap(&res,res))分页查询data:=ResultStruct{UserName:"TestNoSqlInsert",UserEmail:"xxxxx@163.com",}//创建分页参数param:=entity.PageParam{CurrentPage:1,//第几页PageSize:20,//每页多少条Params:dbutil.StructToMap(&data,data),//查询参数}//执行查询操作result,err:=operation.GetDBTemplate("Datasourcename").SelectPage("select*fromxt_message_boardwhereuser_name={user_name}anduser_email={user_email}",param)事务管理//开启事务id,err:=db.Transaction()iferr!=nil{t.Error("TestUpdateTx:"+err.Error())return}res:=ResultStruct{Id:1,UserName:"TestUpdateTx"}//注:这里使用的不是GetDBTemplate,ExecByMap,而是GetDBTemplateTx和ExecByTxMap//使用事务和不使用事务,在调用的函数上,区别就是多了个Txss,err:=operation.GetDBTemplateTx(id,"dbPoolTest").ExecByTxMap("updatext_message_boardsetuser_name={user_name}whereid={id}",dbutil.StructToMap(&res,res))iferr!=nil{//如果有问题就回滚事务db.Rollback(id)t.Error("TestUpdateTx:"+err.Error())return}//提交事务db.Commit(id)想了解更多的话,可以查阅我们的文档哦
评论