This is a creation in Article, where the information may have evolved or changed.
Recently in want to add some like and comment function, third-party system has a variety of restrictions, you want to get a back end, to achieve similar functions, for individuals, the amount of data is not very large, single-machine mysql enough to save all the data, MySQL as the underlying storage is a good choice
Before the company is directly used to github.com/go-sql-driver/mysql
access the database is directly with the write SQL, take out the results and then make their own objects, using the above is not very convenient, readability is not good. Think of the previous study of PHP Laravel framework, the database layer is directly shielded, the user sees only objects, use is very convenient, Java inside this operation basically has become standard practice, go to GitHub to find a bit golang inside there is no similar thing, Sure enough, there's a very mature framework, and github.com/jinzhu/gorm
there's already 7k+ star.
ORM (Object Relation Mapping), objects relationship mapping, is actually the operation of the database encapsulation, the upper layer of developers to screen data manipulation details, developers see is a object, greatly simplifying the development work, improve production efficiency
Well, below I take this comment system as an example, introduce the simple use of Gorm, the following full code: https://github.com/hatlonely/...
Gorm Usage Introduction
Library installation
go get -u github.com/jinzhu/gorm
Database connection
import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql")var db *gorm.DBfunc init() { var err error db, err = gorm.Open("mysql", "<user>:<password>/<database>?charset=utf8&parseTime=True&loc=Local") if err != nil { panic(err) }}
Connection is simple, call the gorm.Open
incoming database address directly
github.com/jinzhu/gorm/dialects/mysql
Is Golang's MySQL driver, which is actually the github.com/go-sql-driver/mysql
author here to remember, re-made a name
Here I use MySQL, actually support basically all the mainstream relational database, connection way slightly different
db.DB().SetMaxIdleConns(10)db.DB().SetMaxOpenConns(100)
You can also use db.DB()
objects to set connection pool information
Table Definition
First, to define a point like table, which is a record that a user at a certain time to a certain article point a like, with IP + UA to identify the user, Title logo article title
type Like struct { ID int `gorm:"primary_key"` Ip string `gorm:"type:varchar(20);not null;index:ip_idx"` Ua string `gorm:"type:varchar(256);not null;"` Title string `gorm:"type:varchar(128);not null;index:title_idx"` Hash uint64 `gorm:"unique_index:hash_idx;"` CreatedAt time.Time}
Gorm tag to identify the constraints in MySQL
To create an index you only need to specify the column directly, here you create two indexes, ip_idx
and title_idx
If you need a multiple-column combination index, the index will be the same name directly; If you need to create a unique index, specify unique_index
Support time type, direct use time.Time
can
Create a table
if !db.HasTable(&Like{}) { if err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&Like{}).Error; err != nil { panic(err) }}
db.CreateTable
You can create a table directly through it, it is very convenient, you can also db.Set
set some additional table properties
Insert
like := &Like{ Ip: ip, Ua: ua, Title: title, Hash: murmur3.Sum64([]byte(strings.Join([]string{ip, ua, title}, "-"))) >> 1, CreatedAt: time.Now(),}if err := db.Create(like).Error; err != nil { return err}
Constructs the given object first, the direct call db.Create()
can insert a record
Delete
if err := db.Where(&Like{Hash: hash}).Delete(Like{}).Error; err != nil { return err}
db.Where()
You can delete a query by constructing db.Delete()
it before you call it.
Inquire
var count interr := db.Model(&Like{}).Where(&Like{Ip: ip, Ua: ua, Title: title}).Count(&count).Errorif err != nil { return false, err}
First Use db.Model()
Select a table, then db.Where()
construct the query condition, you can use the db.Count()
calculated quantity, if you want to get the object, you can use db.Find(&Likes)
or only need to look up a recorddb.First(&Like)
Modify
db.Model(&user).Update("name", "hello")db.Model(&user).Updates(User{Name: "hello", Age: 18})db.Model(&user).Updates(User{Name: "", Age: 0, Actived: false}) // nothing update
I do not have the system update requirements, these examples from the official website, the first is to update a single record, the second is to update the entire record, note that only non-empty fields will be updated, the third example is not updated, in the system design to try to avoid these null values have a special meaning, if you must update, You can use the first method to set a single value
Error handling
In fact, you have seen that basically all of the functions are chain-like, all return to the db
object, any time the call db.Error
can get the error message, very convenient
Transaction
func CreateAnimals(db *gorm.DB) err { tx := db.Begin() if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil { tx.Rollback() return err } if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil { tx.Rollback() return err } tx.Commit() return nil}
Transaction processing is also very simple, with a db.Begin()
declaration to open the transaction, the end of the call, when the tx.Commit()
exception of the calltx.Rollback()
Other
You can also use the following methods to set the log output level and change the log output place
db.LogMode(true)db.SetLogger(gorm.Logger{revel.TRACE})db.SetLogger(log.New(os.Stdout, "\r\n", 0))
Normal SQL is also supported, but it is recommended not to use
Reference links
- Gorm Official Document: http://gorm.io/
- Gorm Github:https://github.com/jinzhu/gorm
Reprint please indicate the source
This article link: http://hatlonely.github.io/20 ...