


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

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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)

UNIONremovesduplicateswhileUNIONALLkeepsallrowsincludingduplicates;1.UNIONperformsdeduplicationbysortingandcomparingrows,returningonlyuniqueresults,whichmakesitsloweronlargedatasets;2.UNIONALLincludeseveryrowfromeachquerywithoutcheckingforduplicates,

You can customize the separator by using the SEPARATOR keyword in the GROUP_CONCAT() function; 1. Use SEPARATOR to specify a custom separator, such as SEPARATOR'; 'The separator can be changed to a semicolon and plus space; 2. Common examples include using the pipe character '|', space'', line break character '\n' or custom string '->' as the separator; 3. Note that the separator must be a string literal or expression, and the result length is limited by the group_concat_max_len variable, which can be adjusted by SETSESSIONgroup_concat_max_len=10000; 4. SEPARATOR is optional

The table can be locked manually using LOCKTABLES. The READ lock allows multiple sessions to read but cannot be written. The WRITE lock provides exclusive read and write permissions for the current session and other sessions cannot read and write. 2. The lock is only for the current connection. Execution of STARTTRANSACTION and other commands will implicitly release the lock. After locking, it can only access the locked table; 3. Only use it in specific scenarios such as MyISAM table maintenance and data backup. InnoDB should give priority to using transaction and row-level locks such as SELECT...FORUPDATE to avoid performance problems; 4. After the operation is completed, UNLOCKTABLES must be explicitly released, otherwise resource blockage may occur.

To select data from MySQL table, you should use SELECT statement, 1. Use SELECTcolumn1, column2FROMtable_name to obtain the specified column, or use SELECT* to obtain all columns; 2. Use WHERE clause to filter rows, such as SELECTname, ageFROMusersWHEREage>25; 3. Use ORDERBY to sort the results, such as ORDERBYageDESC, representing descending order of age; 4. Use LIMIT to limit the number of rows, such as LIMIT5 to return the first 5 rows, or use LIMIT10OFFSET20 to implement paging; 5. Use AND, OR and parentheses to combine

IFNULL()inMySQLreturnsthefirstexpressionifitisnotNULL,otherwisereturnsthesecondexpression,makingitidealforreplacingNULLvalueswithdefaults;forexample,IFNULL(middle_name,'N/A')displays'N/A'whenmiddle_nameisNULL,IFNULL(discount,0)ensurescalculationslike

To delete a view in MySQL, use the DROPVIEW statement; 1. The basic syntax is DROPVIEWview_name; 2. If you are not sure whether the view exists, you can use DROPVIEWIFEXISTSview_name to avoid errors; 3. You can delete multiple views at once through DROPVIEWIFEXISTSview1, view2, view3; the deletion operation only removes the view definition and does not affect the underlying table data, but you need to ensure that no other views or applications rely on the view, otherwise an error may be caused, and the executor must have DROP permissions.

Use MySQL to process JSON data to directly store, query and operate semi-structured data in relational databases. Since version 5.7, JSON types are supported; columns are defined through JSON data types and legal JSON values are inserted, MySQL will automatically verify the syntax; data can be extracted using JSON_EXTRACT() or -> (returns quoted strings) and ->> (returns unquoted values), such as profile->> "$.city" to obtain city names; support filtering JSON values through WHERE clauses, and it is recommended to use generated columns and indexes to improve performance, such as ADDcityVARCHAR(50)GENERA

TheLIKEoperatorinMySQLisusedtosearchforpatternsintextdatausingwildcards;1.Use%tomatchanysequenceofcharactersandtomatchasinglecharacter;2.Forexample,'John%'findsnamesstartingwithJohn,'%son'findsnamesendingwithson,'%ar%'findsnamescontainingar,'\_\_\_\_
