golang gorm operates mysql and gorm basic usage

  • 2020-06-23 00:37:16
  • OfStack

The official operation of golang is a little troublesome, so gorm is used. The following is a brief introduction of gorm

Download gorm:

go get -u github.com/jinzhu/gorm

Introduce gorm into the project:


import (
 "github.com/jinzhu/gorm"
 _ "github.com/jinzhu/gorm/dialects/mysql"
)

Define the db connection information


func DbConn(MyUser, Password, Host, Db string, Port int) *gorm.DB {
 connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", MyUser,Password, Host, Port, Db )
 db, err := gorm.Open("mysql", connArgs)
 if err != nil {
  log.Fatal(err)
 }
 db.SingularTable(true)
 return db
}

Since grom USES orm mapping, you need to define model of the table you want to operate on. In go, you need to define 1 struct, and the name of struct is the name of the table in the database. Note that when gorm looks for the name of the table in the database, it will convert the uppercase letter in your struct to lowercase and add "s" by default. So you can add db.SingularTable (true) to escape the name struct without adding s. I created the table in the database in advance and then used grom to query, or I can use gorm to create the table, I feel that it is still directly created on the database, the operation of modifying the table fields is convenient, grom is only used to query and update the data.

Assuming that the table in the database has been created, the following is the table sentence in the database:


CREATE TABLE `xz_auto_server_conf` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `group_zone` varchar(32) NOT NULL COMMENT ' For example: wanba,changan,aiweiyou,360',
 `server_id` int(11) DEFAULT '0' COMMENT ' Area clothing id',
 `server_name` varchar(255) NOT NULL COMMENT ' Area clothing name ',
 `open_time` varchar(64) DEFAULT NULL COMMENT ' Open take time ',
 `service` varchar(30) DEFAULT NULL COMMENT ' The environment, test The test, formal Mix clothing, wb Let's play ',
 `username` varchar(100) DEFAULT NULL COMMENT 'data Administrator name ',
 `submit_date` datetime DEFAULT NULL COMMENT ' Record submission time ',
 `status` tinyint(2) DEFAULT '0' COMMENT ' State, 0 Untreated, 1 Processed, default is 0',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

When defining model, or struct, for struct, we can define only the specific fields that we need to retrieve from the database:

When gorm escapes the table name, it will replace the capital letter of stuct (except the first letter) with "_", so the following "XzAutoServerConf "will escape the table name corresponding to" xz_auto_server conf "in the database. The corresponding field name will be searched according to the name in tag first. If there is no label defined, it will be searched according to the field defined by struct. The uppercase in the struct field is escaped to "" when searching, for example" GroupZone "looks for the group_zone field in the table


// define struct
type XzAutoServerConf struct {
 GroupZone string `gorm:"column:group_zone"`
 ServerId int
 OpenTime string
 ServerName string
 Status int
}

// Defining a database connection 
type ConnInfo struct {
 MyUser string
 Password string
 Host string
 Port int
 Db string
}

func main () {
cn := ConnInfo{
  "root",
  123456",
  "127.0.0.1",
  3306,
  "xd_data",
 }
  db := DbConn(cn.MyUser,cn.Password,cn.Host,cn.Db,cn.Port)
  defer db.Close() //  Close the database link, defer Closes the database connection at the end of the function 
 var rows []api.XzAutoServerConf
//select 
db.Where("status=?", 0).Select([]string{"group_zone", "server_id", "open_time", "server_name"}).Find(&rows)
//update
 err := db.Model(&rows).Where("server_id=?", 80).Update("status", 1).Error
 if err !=nil {
 fmt.Println(err)
 }
fmt.Println(rows)
}

More grom operation can refer to: https: / / jasperxu github. io/gorm zh /

Now let's look at Golang GORM in use

gorm

gorm is an ORM (object-relational mapping) library that implements database access in go language. Using this library, we can use the object-oriented method, more convenient to the data in the database CRUD(add, delete, change and check).

The basic use

Download the dependent


go get github.com/jinzhu/gorm
go get github.com/go-sql-driver/mysql

The first is the core library.
The second is the mysql driver package.

Connect to database


packae main
import (
 "github.com/jinzhu/gorm"
 _ "github.com/jinzhu/gorm/dialects/mysql"
 "fmt"
)
func main() {
 db, err := gorm.Open("mysql",
 "root:root@/test?charset=utf8&parseTime=True&loc=Local")

 if err != nil {
  fmt.Println(err)
  return
 }else {
  fmt.Println("connection succedssed")
 }
 defer db.Close()

The new data


type User struct {
 ID  int   `gorm:"primary_key"`
 Name string   `gorm:"not_null"`
}
func add() {
 user := &User{Name:"zhangsan"}
 db.Create(user)
}

Delete the data


user := &User{ID:1}
db.delete(user)

Update the data


user := &User{ID:1}
db.Model(user).update("Name","lisi")

Query data


func DbConn(MyUser, Password, Host, Db string, Port int) *gorm.DB {
 connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", MyUser,Password, Host, Port, Db )
 db, err := gorm.Open("mysql", connArgs)
 if err != nil {
  log.Fatal(err)
 }
 db.SingularTable(true)
 return db
}
0

other

Determine whether there is a table corresponding to the structure in the database:


func DbConn(MyUser, Password, Host, Db string, Port int) *gorm.DB {
 connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", MyUser,Password, Host, Port, Db )
 db, err := gorm.Open("mysql", connArgs)
 if err != nil {
  log.Fatal(err)
 }
 db.SingularTable(true)
 return db
}
1

Create a table


func DbConn(MyUser, Password, Host, Db string, Port int) *gorm.DB {
 connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", MyUser,Password, Host, Port, Db )
 db, err := gorm.Open("mysql", connArgs)
 if err != nil {
  log.Fatal(err)
 }
 db.SingularTable(true)
 return db
}
2

These are the basic USES of gorm.

conclusion


Related articles: