


Introducing golang gorm to operate mysql and the basic usage of gorm
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
db.HasTable(User{})
Create table
db.CreateTable(User{})
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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 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

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.

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 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.

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.

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.
