Use Golang to encapsulate an Api framework-Database Operation (introduced by gorm)

Foreword:

It is impossible to operate without a database in a framework. This framework temporarily introduces gorms. If the gorms are not used successfully, you need to consider creating a wheel based on the Golang database driver

  1. Introducing gorm

    // 在 go.mod 中加入
    require github.com/jinzhu/gorm v1.9.12
    

    When introducing the gorm, you may encounter that the crypto resource is blocked by the wall and cannot be pulled. At this time, you need to manually download the gorm installation.

    cd $PATH/pkg/mod/cache/download/golang.org/x/
    git clone  https://github.com/golang/crypto.git
    go mod download				// 重新安装
    
  2. Get MySQL configuration

    About the configuration of MySQL, a configuration file is defined in the conf directory: mysql.go

    package conf
    
    var mysqlConf = map[string]map[string]string{
    	"default": {
    		"host":     "",
    		"password": "",
    		"port":     "",
    		"user":     "",
    		"dbname":   "",
    	},
    }
    
    func GetAllMysqlConf() map[string]map[string]string {
    	return mysqlConf
    }
    
    func GetMysqlConf(key string) map[string]string {
    	if key == "" {
    		key = "default"
    	}
    	return mysqlConf[key]
    }
    

    A variable is defined in this file, which stores the relevant configuration of the database, and the following method to obtain all database configurations and a single configuration

  3. Define Model

    1. A BaseModel object is defined in models / baseModel, and methods for obtaining and releasing database connections are defined on this object

      type BaseModel struct {
      	dbConnect *gorm.DB
      }
      
      func (baseModel BaseModel) getDbConnect() *gorm.DB {
      	var err error
      	mysqlConfig := conf.GetMysqlConf("default")
      
      	fmt.Println(mysqlConfig["user"] + ":" + mysqlConfig["password"] + "@(" + mysqlConfig["host"] + ":" + mysqlConfig["port"] + ")/" + mysqlConfig["dbname"] + "?charset=utf8&parseTime=True&loc=Local")
      
      	baseModel.dbConnect, err = gorm.Open("mysql", mysqlConfig["user"]+":"+mysqlConfig["password"]+"@("+mysqlConfig["host"]+":"+mysqlConfig["port"]+")/"+mysqlConfig["dbname"]+"?charset=utf8&parseTime=True&loc=Local")
      	//defer baseModel.dbConnect.Close()
      	if err != nil {
      		// 打日志
      		log.Println("数据库连接错误----", err)
      		return nil
      	}
      	return baseModel.dbConnect
      }
      
      func (baseModel BaseModel) close() {
      	if baseModel.dbConnect != nil {
      		baseModel.dbConnect.Close()
      	}
      }
      

      The reason for not using defer to write the operation of releasing the database connection in the method of obtaining the database connection is that the execution time of the defer operation is after return and before the function exits. If the operation of releasing the database connection is written in the method of obtaining the database connection, this connection will be released before it is useless .

    2. Define the test model in models / testModel.go and use it in the test controller in 4 below

      type TestModel struct {
      	BaseModel
      }
      
      func (test TestModel) Test() {
      	db := test.getDbConnect()									// 获取连接
      	if db == nil {
      		fmt.Println("db 连接失败")
      	}
      	
        // 查询语句
      	rows, err := db.Raw("sql", ...args).Rows() 
      
      	if err != nil {
      		fmt.Println(err)
      		return
      	}
      	// 这个变量对应数据库中表的字段
      	var a, b, c, d, e, f string							
      	for rows.Next() {
      		rows.Scan(&a, &b, &c, &d, &e, &f)
      		fmt.Println(a, b, c, d, e, f)
      	}
        defer rows.Close()
        
        // 更新语句
        db.Exec("sql", ...args)
      	// 根据 db.Error 和 db.RowsAffected 来判断 释放执行成功
      
      	defer test.close()
      }
      
  4. Used in the controller

    Just call it directly in controller / testController.go

    type TestController struct {
    }
    
    func (t *TestController) Test(w http.ResponseWriter, r *http.Request) {
    
       testModel := models.TestModel{}
       testModel.Test()
    
       fmt.Fprint(w, "this is test.test")
    
    }
    

Note:
1. It is necessary to register the routing of the test controller during the test, and the link configuration of the database must be accurate
2. The sample code address of this blog: https://github.com/zhuchenglin/goweb
3. Creation is not easy , If you need to reprint, please indicate the source: https://www.cnblogs.com/zhuchenglin/p/12731078.html

Guess you like

Origin www.cnblogs.com/zhuchenglin/p/12731078.html