Original author, public number [programmer reading], welcome to pay attention to the public number, reprint the article please indicate the source oh.

In the last article, we explained the process of using the SQL/DATABASE package, the standard library of Go language, to operate the database. Although it is convenient to use the SQL /database package to operate the data, but we need to write each SQL statement, so we may encapsulate it again, so that we can use it better. An open source ORM framework using the existing Go language is a better alternative to encapsulation.

ORM, or Object Relational Mapping, can be simply understood as Mapping data tables in Relational databases to specific data types in programming languages (such as struct), and GORM library is an ORM framework that uses Go language and has very perfect functions and is easy to use.

Let’s explore how to use GORM framework.

features

  • (Has One, Has Many, Belongs To, Many To Many, polymorphism)
  • Hooks (before or after creating/saving/updating/deleting/finding)
  • preload
  • The transaction
  • Composite primary key
  • SQL generator
  • Automatic database migration
  • Custom Logs
  • Extensible, plug-ins can be written based on GORM callbacks

How to install

Installing GORM is as simple as using go Get -u to install the latest GROM framework in the GOPATH directory.

go get -u github.com/jinzhu/gorm
Copy the code

Once installed, you can use the import keyword to import the GORM library, and here we go!

import "github.com/jinzhu/gorm"
Copy the code

Supported databases

GORM framework supports MySQL, SQL Server, Sqlite3, PostgreSQL database driven four, if we want to connect the database, you need to import the different drive packages and define different formats of DSN (Data Source Name).

MySQL

1. The import
import _ "github.com/jinzhu/gorm/dialects/mysql"//import _"github.com/go-sql-driver/mysql"
Copy the code
2. DSN
// User indicates the user name, password indicates the password, and dbname indicates the database name"user:password@/dbname? charset=utf8&parseTime=True&loc=Local"
Copy the code

SQL Server

1. The import
import _ "github.com/jinzhu/gorm/dialects/mssql"
Copy the code
2. DSN
//username indicates the username, password indicates the password,host indicates the host address, port indicates the port number, and database indicates the database name"sqlserver://username:password@host:port? database=dbname"
Copy the code

Sqlite3

1. The import
import _ "github.com/jinzhu/gorm/dialects/sqlite"
Copy the code
2. DSN

The DSN that connects to the Sqlite3 database only needs to specify the path of the Sqlite3 database file, for example:

// Database path/TMP /gorm.dbCopy the code

PostgreSQL

1. The import
import _ "github.com/jinzhu/gorm/dialects/postgres"
Copy the code
2. DSN
//host indicates the host ADDRESS,port indicates the port number,user indicates the user name,dbname indicates the database name, and password indicates the password. Host =myhost port=myport user=gorm dbname=gorm password=mypasswordCopy the code

Connecting to a Database

If you connect to a database, use the gorm.open () method to initialize and return a gorm.db structure. This structure encapsulates all the database operation methods of the GORm framework.

func Open(dialect string, args ... interface{}) (db *DB, err error)Copy the code

Sample code:

package main

import "github.com/jinzhu/gorm"
import _ "github.com/jinzhu/gorm/dialects/mysql"//DSN const DSN ="root:123456@tcp(localhost:3306)/test? charset=utf8&parseTime=True&loc=Local"// Specify the DRIVER const DRIVER ="mysql"

var db *gorm.DB

func init() {
    var err error
    db,err = gorm.Open(DRIVER,DSN)
    iferr ! = nil{ panic(err) } } funcmain(){defer db.close ()// Close before exit // call db to perform specific logic}Copy the code

In the above example, we initialize the gorm.db structure in the init method so that in the following example, database operations can be performed directly using the variable DB.

Basic operation

After using the gorm.open () function to return a gorm.db structure, we can use the methods provided by the gorm.db structure to operate on the database. Let’s demonstrate how to use gorm.db to create, query, update, delete and other basic operations.

Gorm.DB is encapsulated in the SQL.DB structure of the DATABASE/SQL library in Go, because gorm.DB provides many of the same methods as SQL.

func (s *DB) Exec(sql string, values ... interface{}) *DB func (s *DB) Row() *sql.Row func (s *DB) Rows() (*sql.Rows, error) func (s *DB) Scan(dest interface{}) *DBCopy the code

Alternatively, using the DB() method in the gorm.db structure, you can return a SQL.db object as follows:

func (s *DB) DB() *sql.DB
Copy the code

Here are some easier ways to do basic database operations using the gorm.db structure, but before we can do this, we need to define a model as follows:

typeUser struct {Id int // Username string Password string Email string Phone string}Copy the code

We define a structure named User, and GROM supports regular mapping of a structure to a row of a table. Each field in the structure represents a column of the table, and the first letter of the field in the structure must be uppercase.

create

Using the Create() method in gorm.db, GORm inserts a row into the table based on the model passed to the Create() method.

Func (s *DB) Create(value interface{}) *DB // Create a row func (s *DB) NewRecord(value Interface {}) bool // Determine whether the primary key exists according to the self-added IDCopy the code

The sample

func main() {defer db.close () // the specific logic u := &user {Username:"test_one", Password: "testOne123456", Email: "[email protected]", Phone: "13711112222"}
    db.Create(u)
    if db.NewRecord(u){
        fmt.Println("Write failed")}else{
    	fmt.Println("Write succeeded")}}Copy the code

The query

The GROM framework encapsulates the native SQL/Database package with simple methods that can be called directly to map data to the corresponding structure model, such as the following methods:

Func (s *DB) First(out interface{},where. Func (s *DB) Last(out interface{},where. Func (s *DB) Find(out interface{},where. Func (s *DB) Count(value interface{}) *DBCopy the code

The sample code

//Find method example funcfind() {var users = make([]*User, 0) db.model (&User2{}).find (&users) fmt.println (users)} //First method example funcfirst()  {
    var user1,user2 User
    db.First(&user1)
    fmt.Println(user1)
    db.First(&user2,"id = ?",20) fmt.println (user2)} //Last method example funclast()  {
    var user1,user2 User
    db.Last(&user1)
    fmt.Println(user1)
    db.First(&user2,"id = ?",19) fmt.println (user2)} //Count method example funccount()  {
    var count int
    db.Model(&User{}).Count(&count)
    fmt.Println(count)
}
Copy the code

update

Data can be updated using gorm.db’s Save() or Update(),UpdateColumn(),UpdateColumns(),Updates(), etc. The latter four methods need to be used in conjunction with the Model() method.

Func (s *DB) Save(value interface{}) *DB func (s *DB) Model(value interface{}) *DB Func (s *DB) Update(attrs... interface{}) *DB func (s *DB) UpdateColumn(attrs ... interface{}) *DB func (s *DB) UpdateColumns(values interface{}) *DB func (s *DB) Updates(values interface{}, ignoreProtectedAttrs ... bool) *DBCopy the code

Code sample

//Save() method example funcsave(){
    u := &User{}
    db.First(u)
    u.Email = "[email protected]"Db.save (u) fmt.println (u)} //Update method example funcupdate() {
    u := &User{}
    db.First(u)
    db.Model(u).Update("username"."hello"} //Updates method example funcupdates() {
    u := &User{}
    db.First(u)
    db.Model(&u).Updates(map[string]interface{}{"username": "hello2"})}Copy the code

delete

Records that meet the criteria can be easily deleted using the Delete() method of gorm.db. Here is the definition of the Delete() method:

//value If there is a primary key ID, it is included in the criteria and passeswhereFunc (s *DB) Delete(value interface{},where. interface{}) *DBCopy the code

The sample code

func delete(){defer db.close () u := &user {Id: 16} db.delete (u)// defer db.delete (&user {},"username = ? "."test_one")// Delete according to additional condition}Copy the code

summary

In this article we are just going to show you how to connect to and easily manipulate a database using the GROM framework, but there are many more advanced features of the GROM framework that make development simpler. We will cover these in more detail in a future article.


Your attention is the biggest encouragement on my writing road!