Introduction to GORM Library of gorang database programming

We know the process of using the sql/database package of the standard library of Go language to operate the database. Although it is very convenient to use the sql/database package to operate the data, we need to write each SQL statement ourselves. Therefore, we may encapsulate it again for better use, and using the existing open source ORM framework of Go language is a better way to replace our own encapsulation.

ORM, namely object relational mapping, can be simply understood as mapping the data table in the relational database to the specific data type (such as struct) in the programming language, and GORM library is an ORM framework implemented in Go language with perfect functions and easy to use.

Let's explore how to use GORM framework!

characteristic

  • Association (Has One, Has Many, Belongs To, Many To Many, polymorphic)
  • Hooks (before or after creating / saving / updating / deleting / finding)
  • Preload
  • affair
  • Composite primary key
  • SQL generator
  • Automatic database migration
  • Custom log
  • Extensibility, plug-ins can be written based on GORM callback

How to install

Installing GORM is very simple. You can use go get -u to install the latest GROM framework in the GOPATH directory.

go get -u github.com/jinzhu/gorm

After installation, you can use the import keyword to import the GORM library and start using it!

import "github.com/jinzhu/gorm"

Supported databases

GORM framework supports four database drivers: MySQL, SQL server, SQLite3 and PostgreSQL. If we want to connect these databases, we need to import different driver packages and define DSN(Data Source Name) in different formats.

MySQL

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

SQL Server

1. Import
import _ "github.com/jinzhu/gorm/dialects/mssql"
2. DSN
//username refers to the user name, password refers to the password, host refers to the host address, port refers to the end slogan, and database refers to the database name
"sqlserver://username:password@host:port?database=dbname"

Sqlite3

1. Import
import _ "github.com/jinzhu/gorm/dialects/sqlite"
2. DSN

The DSN connecting Sqlite3 database only needs to specify the path of Sqlite3 database file, such as:

//Database path
/tmp/gorm.db

PostgreSQL

1. Import
import _ "github.com/jinzhu/gorm/dialects/postgres"
2. DSN
//Host refers to the host address, port refers to the end slogan, user refers to the user name, dbname refers to the database name, and password refers to the password
host=myhost port=myport user=gorm dbname=gorm password=mypassword

Connect database

Above, we have defined DSN s for connecting different databases. Next, we will demonstrate how to use GORM The open () method initializes and returns a GORM DB structure, which encapsulates all database operation methods of GORM framework. The following is GORM Definition of open() method:

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

Example code:

package main

import "github.com/jinzhu/gorm"
import _ "github.com/jinzhu/gorm/dialects/mysql"//Import the driver package connecting to MySQL database

//DSN
const DSN = "root:123456@tcp(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local"
//Specify drive
const DRIVER = "mysql"

var db *gorm.DB

func init() {
    var err error
    db,err = gorm.Open(DRIVER,DSN)
    if err != nil{
        panic(err)
    }
}

func main(){
    defer db.Close()//Execute close before exiting
    //Call db to execute specific logic
}

In the above example, we initialize Gorm in the init method db structure, so in the following example, you can directly use the variable db for database operation.

basic operation

Use Gorm The open() function returns a Gorm After the DB structure, we can use Gorm The method provided by the DB structure operates the database. Next, we demonstrate how to use Gorm DB performs basic operations such as creation, query, update and deletion.

Actually Gorm DB is SQL in the database/sql Library of Go language It is encapsulated on the DB structure because Gorm DB provides many and SQL DB, as shown below:

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{}) *DB

In addition, use Gorm The DB() method in the DB structure can return an SQL DB object, as follows:

func (s *DB) DB() *sql.DB

The following shows how to use Gorm There are some simpler methods in DB structure for basic database operations. However, before demonstration, we need to define a model as follows:

type User struct {
    Id       int   //Self incrementing id of the corresponding data table
    Username string
    Password string
    Email    string
    Phone    string
}

We define a structure named User. Gram supports mapping the structure into a row of a data table according to rules. Each field of the structure represents the column of the data table, and the field initials of the structure must be uppercase.

establish

Use GORM For the Create() method in dB, GORM will insert a row into the data table according to 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 increment id

Examples

func main() {
    defer db.Close()
    //Concrete logic
    u := &User{Username: "test_one", Password: "testOne123456", Email: "test_one@163.com", Phone: "13711112222"}
    db.Create(u)
    if db.NewRecord(u){
        fmt.Println("Write failed")
    }else{
        fmt.Println("Write successful")
    }
}

query

The gram framework encapsulates simple methods based on the native sql/database package, which can be directly called to map the data to the corresponding structure model. It is very simple to use, such as the following methods:

//Return to the first item
func (s *DB) First(out interface{}, where ...interface{}) *DB
//Return to the last one
func (s *DB) Last(out interface{}, where ...interface{}) *DB
//Return qualified content
func (s *DB) Find(out interface{}, where ...interface{}) *DB
//Return Count(*) result
func (s *DB) Count(value interface{}) *DB

Sample code

//Find method sample official account: Advanced notes of code farming programming
func find() {
    var users = make([]*User, 0)
    db.Model(&User2{}).Find(&users)
    fmt.Println(users)
}

//First method example
func first()  {
    var user1,user2 User
    db.First(&user1)
    fmt.Println(user1)
    db.First(&user2,"id = ?",20)
    fmt.Println(user2)
}

//Last method example
func last()  {
    var user1,user2 User
    db.Last(&user1)
    fmt.Println(user1)
    db.First(&user2,"id = ?",19)
    fmt.Println(user2)
}

//Count method example
func count()  {
    var count int
    db.Model(&User{}).Count(&count)
    fmt.Println(count)
}

to update

To update data, you can use Gorm DB's Save() or Update(),UpdateColumn(),UpdateColumns(),Updates() and other methods. The latter four methods need to be used together with the Model() method.

func (s *DB) Save(value interface{}) *DB

func (s *DB) Model(value interface{}) *DB
//The following methods need to be used together with the Model method to specify the conditions for updating data through the Model method
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) *DB

Code example

//Example of Save() method
func save(){
    u := &User{}
    db.First(u)
    u.Email = "test@163.com"
    db.Save(u)
    fmt.Println(u)
}

//Update method example
func update() {
    u := &User{}
    db.First(u)
    db.Model(u).Update("username", "hello")
}

//Updates method example
func updates() {
    u := &User{}
    db.First(u)
    db.Model(&u).Updates(map[string]interface{}{"username": "hello2"})
}

Give me a compliment to prove that you still love me

delete

Use Gorm DB's Delete() method can simply delete records that meet the conditions. The following is the definition of the Delete() method:

//If value has a primary key id, it is included in the judgment conditions. Other conditions can be specified through where
func (s *DB) Delete(value interface{}, where ...interface{}) *DB

Sample code

func delete(){
    defer db.Close()
    u := &User{Id: 16}
    db.Delete(u)//According to id
    db.Delete(&User{},"username = ? ","test_one")//Delete according to additional conditions
}

Summary

In this article, we just explain how to connect and simply operate the database using the GROM framework. In fact, the GROM framework has many more advanced functions, which can make our development more concise. We will explain it in detail in later articles.

Everyone you ordered was watching. I took it seriously and liked it

Added by Pr0digy on Thu, 17 Feb 2022 06:45:39 +0200