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

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

May 17, 2021 pm 04:45 PM
golang gorm mysql

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"
)
Copy after login

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
}
Copy after login

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;
Copy after login

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
}
Copy after login
//定义数据库连接
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)
}
Copy after login

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
Copy after login

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()
Copy after login

Add data

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

Delete data

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

Update data

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

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)
Copy after login

Others

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

db.HasTable(User{})
Copy after login

Create table

db.CreateTable(User{})
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Solution to MySQL encounters 'Access denied for user' problem Solution to MySQL encounters 'Access denied for user' problem Apr 11, 2025 pm 05:36 PM

How to solve the MySQL "Access denied for user" error: 1. Check the user's permission to connect to the database; 2. Reset the password; 3. Allow remote connections; 4. Refresh permissions; 5. Check the database server configuration (bind-address, skip-grant-tables); 6. Check the firewall rules; 7. Restart the MySQL service. Tip: Make changes after backing up the database.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Navicat's automatic backup of MySQL data Navicat's automatic backup of MySQL data Apr 11, 2025 pm 05:30 PM

Steps to automatically back up MySQL data using Navicat: Install and connect to the MySQL server. Create a backup task, specifying the backup source, file location, and name. Configure backup options, including backup type, frequency, and retention time. Set up an automatic backup plan, enable automatic backup, set time and frequency. Preview the backup settings and perform the backup. Monitor backup progress and history.

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

See all articles