gorm operates mysql

content

1. Introduction to gorm

Second, gorm installation

Three, gorm model definition

1. Introduction to ORM

2, gorm model definition

3. gorm model label

4. Define the table name

5、gorm.Model

6. Automatic update time

Four, gorm connection database

1. Configure DSN (Data Source Name)

2. Use gorm.Open to connect to the database

3. gorm debugging mode

4. gorm connection pool


1. Introduction to gorm

GORM is the most popular database ORM operation library in Golang at present. It is also friendly to developers. It is very convenient and simple to use. It is mainly used to map struct types and database table records. When operating the database, there is no need to write Sql code directly. Here Mainly introduces MySQL database.

GORM library github address: https://github.com/go-gorm/gorm

Second, gorm installation

Operating MySQL requires the installation of two packages:

  • MySQL driver package
  • GORM packages use the go get command to install dependencies

//安装MySQL驱动
go get -u gorm.io/driver/mysql
//安装gorm包
go get -u gorm.io/gorm

import package

import (
  "gorm.io/driver/mysql"
  "gorm.io/gorm"
)

Three, gorm model definition

1. Introduction to ORM

The ORM framework requires a pre-defined model to operate the database. The model can be understood as a data model as a medium for operating the database.

between.

E.g:

  • The data read from the database will be saved to the pre-defined model object first, and then we can get the data we want from the model object.
  • Inserting data into the database is also to create a new model object first, then save the data you want to save to the model object, and then save the model object to the database.

In golang, the gorm model definition is implemented through struct, so that we can implement the mapping between struct type and mysql table data through the gorm library.

Tip: gorm is responsible for translating the read and write operations of the model into SQL statements, and then gorm converts the results returned by the database after executing the SQL statements into the model objects we defined.

2, gorm model definition

The gorm model definition is mainly to add field labels to the struct type definition to describe the implementation. Let's see a complete example below. If there is a commodity table, the table structure is as follows

CREATE TABLE `food` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID,商品Id',
  `name` varchar(30) NOT NULL COMMENT '商品名',
  `price` decimal(10,2) unsigned  NOT NULL COMMENT '商品价格',
  `type_id` int(10) unsigned NOT NULL COMMENT '商品类型Id',
  `createtime` int(10) NOT NULL DEFAULT 0 COMMENT '创建时间',
   PRIMARY KEY (`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8

The model is defined as follows

//字段注释说明了gorm库把struct字段转换为表字段名长什么样子。
type Food struct {
	Id         int  //表字段名为:id
	Name       string //表字段名为:name
	Price      float64 //表字段名为:price
	TypeId     int  //表字段名为:type_id
	
 //字段定义后面使用两个反引号``包裹起来的字符串部分叫做标签定义,这个是golang的基础语法,不同的库会定义不同的标签,有不同的含义
	CreateTime int64 `gorm:"column:createtime"`  //表字段名为:createtime
}

By default gorm uses Snake Case naming style for struct field names to convert to mysql table field names (needs to be converted to lowercase letters).

According to the default convention of gorm, the above example only needs to use the gorm:"column:createtime" tag to define the table field name for the CreateTime field, and use the default value for others.

Tip: The Snake Case naming style is to separate each word with an underscore (_), for example: CreateTime's Snake Case style is named create_time

3. gorm model label

Through the above example, you can see that you can define the column name (table field name) of the struct field through a tag definition syntax like gorm:"column:createtime".

gorm标签语法:gorm:"标签定义"

In the label definition section, multiple label definitions can be separated by a semicolon (;), for example to define column names:

gorm:"column:列名"

The commonly used tags of gorm are as follows:

Label

illustrate

example

column

Specify column names

gorm:"column:createtime"

primaryKey

Specify the primary key

gorm:"column:id; PRIMARY_KEY"

-

ignore fields

gorm:"-" can ignore the struct field, and the ignored fields do not participate in the read and write operations of gorm

4. Define the table name

You can define the table name of the model by defining the TableName function of the struct type

Take the example above:

//设置表名,可以通过给Food struct类型定义 TableName函数,返回一个字符串作为表名
func (v Food) TableName() string {
	return "food"
}

        Suggestion: By default, the table name is defined for the model. Sometimes the definition model is only used to receive the results of handwritten sql query. In this case, there is no need to define the table name; manually specify the table name through the gorm function Table(), and neither The TableName function needs to be defined for the model.

5、gorm.Model

GORM defines a gorm.Model structure that includes the fields ID, CreatedAt, UpdatedAt, DeletedAt.

// gorm.Model 的定义
type Model struct {
  ID        uint           `gorm:"primaryKey"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt gorm.DeletedAt `gorm:"index"`
}

In order to embed it into our structure, we can include these fields, similar to the effect of inheritance.

type User struct {
  gorm.Model // 嵌入gorm.Model的字段
  Name string
}

6. Automatic update time

GORM convention uses CreatedAt, UpdatedAt to track creation/update time. If such a field is defined, GORM will automatically populate the current time when it is created or updated.

To use fields with different names, you can configure autoCreateTime, autoUpdateTime tags

If you want to store UNIX (milli/nano) second timestamps instead of time, simply change time.Time to int.

example:

type User struct {
  CreatedAt time.Time // 默认创建时间字段, 在创建时,如果该字段值为零值,则使用当前时间填充
  UpdatedAt int       // 默认更新时间字段, 在创建时该字段值为零值或者在更新时,使用当前时间戳秒数填充
  Updated   int64 `gorm:"autoUpdateTime:nano"` // 自定义字段, 使用时间戳填纳秒数充更新时间
  Updated   int64 `gorm:"autoUpdateTime:milli"` //自定义字段, 使用时间戳毫秒数填充更新时间
  Created   int64 `gorm:"autoCreateTime"`      //自定义字段, 使用时间戳秒数填充创建时间
}

Four, gorm connection database

gorm supports a variety of databases, here mainly introduces mysql, there are two main steps to connect mysql:

1) Configure DSN (Data Source Name)

2) Use gorm.Open to connect to the database

1. Configure DSN (Data Source Name)

The gorm library uses dsn as a parameter to connect to the database. The dsn is called the data source name when translated, and is used to describe the database connection information. Generally, it contains database connection address, account number, password and other information.

DSN format:

[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]

mysql connection dsn example:

//mysql dsn格式
//涉及参数:
//username   数据库账号
//password   数据库密码
//host       数据库连接地址,可以是Ip或者域名
//port       数据库端口
//Dbname     数据库名
username:password@tcp(host:port)/Dbname?charset=utf8&parseTime=True&loc=Local

//填上参数后的例子
//username = root
//password = 123456
//host     = localhost
//port     = 3306
//Dbname   = tizi365
//后面K/V键值对参数含义为:
//  charset=utf8 客户端字符集为utf8
//  parseTime=true 支持把数据库datetime和date类型转换为golang的time.Time类型
//  loc=Local 使用系统本地时区
root:123456@tcp(localhost:3306)/tizi365?charset=utf8&parseTime=True&loc=Local

//gorm 设置mysql连接超时参数
//开发的时候经常需要设置数据库连接超时参数,gorm是通过dsn的timeout参数配置
//例如,设置10秒后连接超时,timeout=10s
//下面是完成的例子
root:123456@tcp(localhost:3306)/tizi365?charset=utf8&parseTime=True&loc=Local&timeout=10s

//设置读写超时时间
// readTimeout - 读超时时间,0代表不限制
// writeTimeout - 写超时时间,0代表不限制
root:123456@tcp(localhost:3306)/tizi365?charset=utf8&parseTime=True&loc=Local&timeout=10s&readTimeout=30s&writeTimeout=60s

2. Use gorm.Open to connect to the database

With the dsn parameters configured above, you can use gorm to connect to the database. The following is an example of connecting to the database

package main

import (
  "gorm.io/driver/mysql"
  "gorm.io/gorm"
)

func main()  {
    //配置MySQL连接参数
	username := "root"  //账号
	password := "123456" //密码
	host := "127.0.0.1" //数据库地址,可以是Ip或者域名
	port := 3306 //数据库端口
	Dbname := "tizi365" //数据库名
	timeout := "10s" //连接超时,10秒
	
	//拼接下dsn参数, dsn格式可以参考上面的语法,这里使用Sprintf动态拼接dsn参数,因为一般数据库连接参数,我们都是保存在配置文件里面,需要从配置文件加载参数,然后拼接dsn。
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s", username, password, host, port, Dbname, timeout)
	//连接MYSQL, 获得DB类型实例,用于后面的数据库读写操作。
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("连接数据库失败, error=" + err.Error())
	}
	//延时关闭数据库连接
	defer db.Close()
}

3. gorm debugging mode

In order to facilitate debugging and understand what kind of SQL statement is executed by gorm operation, you need to open the debug log during development, so that gorm will print out each SQL statement executed.

Use the Debug function to execute the query

result := db.Debug().Where("username = ?", "tizi365").First(&u)

4. gorm connection pool

In high concurrency practice, in order to improve the utilization rate of database connections and avoid the performance consumption caused by repeated establishment of database connections, database connection pooling technology is often used to maintain database connections.

gorm comes with a database connection pool, which is very simple to use, just set the database connection pool parameters.

Database connection pool usage example:

Define the tools package to be responsible for database initialization (Note: With the help of the connection pool description, generally when operating the database, the database connection can be encapsulated into a package separately)

//定义一个工具包,用来管理gorm数据库连接池的初始化工作。
package tools

//定义全局的db对象,我们执行数据库操作主要通过他实现。
var _db *gorm.DB

//包初始化函数,golang特性,每个包初始化的时候会自动执行init函数,这里用来初始化gorm。
func init() {
    ...忽略dsn配置,请参考上面例子...
    
    // 声明err变量,下面不能使用:=赋值运算符,否则_db变量会当成局部变量,导致外部无法访问_db变量
    var err error
    //连接MYSQL, 获得DB类型实例,用于后面的数据库读写操作。
    _db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
		panic("连接数据库失败, error=" + err.Error())
	}
     
    sqlDB, _ := db.DB()

    //设置数据库连接池参数
    sqlDB.SetMaxOpenConns(100)   //设置数据库连接池最大连接数
    sqlDB.SetMaxIdleConns(20)   //连接池最大允许的空闲连接数,如果没有sql任务需要执行的连接数大于20,超过的连接会被连接池关闭。
}

//获取gorm db对象,其他包需要执行数据库查询的时候,只要通过tools.getDB()获取db对象即可。
//不用担心协程并发使用同样的db对象会共用同一个连接,db对象在调用他的方法的时候会从数据库连接池中获取新的连接
func GetDB() *gorm.DB {
	return _db
}

Example of use:

package main
//导入tools包
import tools

func main() {
    //获取DB
    db := tools.GetDB()
    
    //执行数据库查询操作
    u := User{}
	//自动生成sql: SELECT * FROM `users`  WHERE (username = 'tizi365') LIMIT 1
	db.Where("username = ?", "tizi365").First(&u)
}

Note: After using the connection pool technology, do not call db.Close to close the database connection after using the db, which will cause the entire database connection pool to close, resulting in no available connections in the connection pool.

Guess you like

Origin blog.csdn.net/demored/article/details/124325939