Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use additions, deletions, modifications and queries in Go Micro Service practice

Shulou Source: shulou.com Published: 2022-06-03 01:55:53 10月03日 Update

This article mainly introduces "how to use additions, deletions, modifications and queries in the practice of Gomicro services". In daily operation, I believe many people have doubts about how to use additions, deletions, modifications and queries in the practice of Goe services. I hope it will be helpful to answer the doubts about how to use additions, deletions, modifications and searches in the practice of Goe services. Next, please follow the editor to study!

Let's start with the model layer and talk about the API and encapsulation details of go-zero. First of all, the API of the model layer connection is concentrated in core/stores. Let's first take a look at manipulating databases such as mysql, and we came to core/stores/sqlx with the API method, so we will use a few articles to give a general introduction to the use and design ideas of sqlx.

Quick use of func main () {/ / 1 const datasource = "user:password@/dbname" mysqlDB: = sqlx.NewMysql (datasource) / / 2 um: = model.NewUserModel (mysqlDB, "User") / / 3 ul: = logic.NewUserLogic (um) / / 4 engine.AddRoutes (nginxApi (ul)) engine.Start ()} / / NewUserModel NewUserLogic is similar to func NewUserModel (conn sqlx.SqlConn, table string) * UserModel {return & UserModel {conn: conn, table: table}} / / nginxApi injects logic into handle Bind routing and handlerfunc nginxApi (ul * logic.UserLogic) [] rest.Route {return [] rest.Route {{Method: http.MethodGet, Path: "/ user/:id", / user/54er6 Handler: handler.NewUserHandler (ul). GetUserById,}}

To sum up:

NewMysql creates a database connection

Create the corresponding model and pass the connection into "the corresponding NewModel needs to be written by the developer"

Model provides services for the upper layer of logic

Inject logic into handler, bind handler to routing, and enable Server

In this way, the simplest structure of model-logic-handler comes out. Then take a look at how the data is manipulated at the model layer:

Var userBuilderQueryRows = strings.Join (builderx.FieldNames (& User {}), ",") type User struct {Avatar string `db: "avatar" `/ / avatar UserName string `db: "user_name"` / / name Sex int `db: "sex" `/ / 1 male, 2 female MobilePhone string `db: "mobile_phone"` / / Mobile number} func (um * UserModel) Insert (user * User) (int64, error) {const insertsql = `insert into `+ um.table+` (`+ userBuilderQueryRows+`) values Res, err: = um.conn.Exec (insertsql, user.Avatar, user.UserName, user.Sex, user.MobilePhone) if err! = nil {logx.Errorf ("insert User Position Model Model err,err=%v", err) return-1, err} id, err: = res.LastInsertId () if err! = nil {logx.Errorf ("insert User Model to Id parse id err,err=%v") Err) return-1, err} return id, nil} func (um * UserModel) FindOne (uid int64) (* User, error) {var user User / / query const querysql = `select `+ userBuilderQueryRows+ `from` + um.table+ `where id=? Limit 1`err: = um.conn.QueryRow (& user, querysql, uid) if err! = nil {logx.Errorf ("userModile.findOne error, id=%d,err=%s", uid, err.Error ()) if err= = sqlx.ErrNotFound {return nil, ErrNotFound} return nil, err} return & user Nil}

Insert/update/delete:conn.Exec (insertsql/updatesql/deletesql, args...)

Query:conn.QueryRow (& model, querysql, args...)

This is the simplest structure of crud: first build the model, then manipulate the model to operate.

Code structure file name functions bulkinserter.go batch insertion mysql.goNewMysqlorm.go parsing, serializing model operation sqlconn.go abstract crud operation interface tx.go transaction operation

From the interface relationship between sqlconn.go:

You can see that commonSqlConn and txSession are really implemented. Let's start with an overall introduction to the functions of API:

API parameter functions Exec (query, args...) sql, sql parameter insert/update/deletePrepare (query) sql precompiled sqlQueryRow (& model, query, args...) model, sql, sql parameters query a row of data and assign values to "model" QueryRowPartial (& model, query, args...) model, sql, sql parameters as above But select sql can select only part of model's column "set off Partial" QueryRows/QueryRowsPartial ditto query multi-line APITransact (func (session Session) error) transaction operation to wrap the operation in the parameters with a transaction, developers only need to focus on the preparation of the functions in the parameters, and the study on "how to use additions, deletions, modifications and queries" is over. I hope to be able to solve everyone's 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!

Tags: Parameters practice data learning transactions at the same time structure next functions functions developers interfaces databases articles methods more routing help development query Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi OPPO Reno Linux Microsoft MariaDB