Home  >  Article  >  Backend Development  >  Introducing golang gorm to operate mysql and the basic usage of gorm

Introducing golang gorm to operate mysql and the basic usage of gorm

藏色散人
藏色散人forward
2021-05-17 16:45:133894browse

The following tutorial column of golang will introduce to you the basic usage of golang gorm to operate mysql and gorm. I hope it will be helpful to friends in need!

golang The official one is a bit troublesome to operate mysql, so I used gorm. Here is a brief introduction to the use 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 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 is the orm mapping used, Therefore, you need to define the model of the table to be operated. In go, you need to define a struct. The name of the struct corresponds to the table name in the database. Note that when gorm searches for the struct name corresponding to the table name in the database, it will default to the name in your struct. Convert uppercase letters to lowercase and add "s", so you can add db.SingularTable(true) to let grom escape the struct name without adding s. I created the table in the database in advance and then used grom to query it. You can also use gorm to create the table. I feel that it is better to create the table directly on the database. It is convenient to modify the table fields. Grom is only used to query and update data. .

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

CREATE TABLE `xz_auto_server_conf` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `group_zone` varchar(32) NOT NULL COMMENT '大区例如:wanba,changan,aiweiyou,360',
 `server_id` int(11) DEFAULT '0' COMMENT '区服id',
 `server_name` varchar(255) NOT NULL COMMENT '区服名称',
 `open_time` varchar(64) DEFAULT NULL COMMENT '开服时间',
 `service` varchar(30) DEFAULT NULL COMMENT '环境,test测试服,formal混服,wb玩吧',
 `username` varchar(100) DEFAULT NULL COMMENT 'data管理员名称',
 `submit_date` datetime DEFAULT NULL COMMENT '记录提交时间',
 `status` tinyint(2) DEFAULT '0' COMMENT '状态,0未处理,1已处理,默认为0',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Define model, that is, struct. When specifying struct, we can only define what we need Specific fields retrieved from the database:

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

//定义struct
type XzAutoServerConf struct {
 GroupZone string `gorm:"column:group_zone"`
 ServerId int
 OpenTime string
 ServerName string
 Status int
}
//定义数据库连接
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() // 关闭数据库链接,defer会在函数结束时关闭数据库连接
 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)
}

For more grom operations, please refer to: https://jasperxu.github.io/gorm-zh/

Let’s take a look at Golang GORM usage

gorm

gorm is the go language ORM (Object Relational Mapping) library that implements database access in . Using this library, we can use object-oriented methods to more conveniently perform CRUD (add, delete, modify, query) on the data in the database.

Basic usage

Download dependencies

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

The first one is the core library.

The second one 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()

Add data

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

Delete data

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

Update data

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

Query data

// query all
var users []User
db.Find(&users)
fmt.Println(users)
// query one
user := new (User)
db.First(user,1)
fmt.Println(user)

Others

##Judgment database Is there a table corresponding to the structure:

db.HasTable(User{})

Create table

db.CreateTable(User{})

The above is the basic usage of gorm.

The above is the detailed content of Introducing golang gorm to operate mysql and the basic usage of gorm. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete