Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The basic Operation method of golang Database

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "the basic operation method of golang database". In the daily operation, I believe that many people have doubts about the basic operation method of golang database. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "basic operation method of golang database". Next, please follow the editor to study!

Golang operation database generally uses the open source project gorm, which has more than 15000 star and has more comprehensive functions.

Simple addition, deletion, modification and search

Hibernate, similar to java, encapsulates data into structures (java to objects) for operation

Package modelsimport ("fmt"github.com/astaxie/beego"github.com/jinzhu/gorm"riskcontrol/database"riskcontrol/utils/snowflake"time") const (score = "user_score") type ScoreModel struct {BaseModel UserId string `json: "user_id", gorm: "type:varchar (18); not null Comment:' user id'; "`Score int32 `json:" score ", gorm:" type:int;null;comment:' score'"`BindFacebook bool `json:" bind_facebook ", gorm:" type:boolean;not null " Comment:' Chinese name'"`/ / IsValid bool` json:"-", gorm:" type:boolean;not null;default:1 Whether comment:' is valid (0: invalid, 1: valid)'"`} func init () {database.GetDB (). AutoMigrate (& ScoreModel {})} / * * set the matching table name * / func (ScoreModel) TableName () string {return score} func (userMode * ScoreModel) BeforeCreate (scope * gorm.Scope) error {id Err: = snowflake.NewSnowFlake (). Generate () if err! = nil {beego.Error ("snowflake get id error", err) return err} currentTime: = time.Now () scope.SetColumn ("Id", id) scope.SetColumn ("CreateTime", currentTime) scope.SetColumn ("UpdateTime") CurrentTime) return nil} func (userMode * ScoreModel) BeforeUpdate (scope * gorm.Scope) error {currentTime: = time.Now () scope.SetColumn ("UpdateTime", currentTime) return nil} func GetScoreByUserId (userId string) (ScoreModel,error) {var userScore ScoreModel err: = database.GetDB (). Where (& ScoreModel {UserId:userId}). Last (& userScore). Error return userScore,err} func InsertScore (userId string,score int32,bindFacebook bool AppId string) bool {scoreModel: = ScoreModel {UserId:userId,Score:score,BindFacebook:bindFacebook} scoreModel.AppId = appId if err: = database.GetDB () .Create (& scoreModel) .Error Err! = nil {beego.Error ("AddScore error", err) return false} database.GetDB () .NewRecord (scoreModel) return true} func UpdateScore (id int64, addScore int32,bindFacebook bool) bool {ScoreModel: = ScoreModel {Score:addScore BindFacebook:bindFacebook} ScoreModel.ID = id database.GetDB () .Model (& ScoreModel) .Update (& ScoreModel) return false} Custom sql Update func UpdateScore (id int64, addScore int32,bindFacebook bool) bool {sql: = fmt.Sprintf ("UPDATE user_score SET score = score +% d, bind_facebook =% tjinghee timekeeper now () where id =% d", addScore,bindFacebook Id) res: = database.GetDB () .Exec (sql) num:= res.RowsAffected if num > 0 {return true} return false} query func GetScoreHisByUserId (userId string,id string,up bool) ([] dto.ScoreHisDto,error) {var scoreHis [] dto.ScoreHisDto partitionKey,_: = getPartitionKey () keyList: = [] int {partitionKey,partitionKey-1 PartitionKey-2} sqlScript: = "SELECT id, create_time, remark, (score_after-score_before) / 100 as add_score FROM score_his WHERE" if id! = "" {if up = = true {sqlScript + = fmt.Sprintf ("id >% s and", id)} else {sqlScript + = fmt.Sprintf ("id <% s and" Id)}} database.GetDB () .Raw (sqlScript + "user_id =? And partition_key in (?) Order by id desc limit 20 ", userId, keyList) .Scan (& scoreHis) var err error return scoreHis,err}

The structure of ScoreHisDto is

Type ScoreHisDto struct {Id string `json: "id" `Remark string `json: "remark" `CreateTime time.Time `json: "createTime" `AddScore float32 `json: "addScore" `}

Note that there is a pit here. The field queried by sql will be automatically converted to hump createTime; after being queried by create_time. Unlike java mybatis, mybatis needs to set the alias createTime for field create_time in sql and map it to dto to createTime.

Transaction var tx * gorm.DB// opens transaction tx = database.GetDB () .Begin () sql1: = "" tx.Exec (sql1) sql2: = "" tx.Exec (sql2) / / commit transaction tx.Commit () exception handling

Since go does not have a try...catch...finally, it is troublesome to roll back transactions before each return in the code snippet. At this point, you can use the golang to defer statement, which can do something before the method return, as shown in the following example:

Var err errorvar tx * gorm.DB// predefined methods if the program is abnormal, roll back the transaction defer func () {if err! = nil & & tx! = nil {beego.Error (err, "tx rollback...") before the method return Tx.Rollback ()} () at this point, the study on "basic operating methods of golang database" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report