Golang connect to the database using Gorm notes

Chinese documents Address: https://jasperxu.github.io/gorm-zh/

1. Basic Operation

  1) connected to the database: db, err: = gorm.Open (...)

  2) Read data:

    You need to read data defined struct , by mapping the variable name assignment and an object column name, the field name listed in lowercase serpentine + _, can reset the column name.

  For example (from the manual): 

the User type struct { 
  ID uint              // column id` called ` 
  the Name String          // column named name`` 
  Birthday time.time   // column birthday` named ` 
  createdAt time.time // column created_at` named` 
} 

/ / Reset column names 
of the type Animal struct { 
    AnimalId int64 `GORM: " column: beast_id " `          // set beast_id` column called ` 
    Birthday time.time` GORM: " column: day_of_the_beast " ` // set column called` day_of_the_beast `
    Int64 `GORM Age: " column: age_of_the_beast " ` // set age_of_the_beast` column called ` 
}

  Queries api:

// Get the first record, ordered by primary key 
db.First (& User)
 /// / the SELECT * the FROM Users the ORDER BY ID. 1 the LIMIT; 

// Get the last record, ordered by primary key 
db.Last (& User)
 / // / * the SELECT the FROM Users the ORDER bY ID DESC the LIMIT. 1; 

// All recordings were acquired 
db.Find (& Users)
 /// / the SELECT * the FROM Users; 

// using the master key record acquisition / this can be done directly where. . 
db.First (& User, 10 )
 /// / the SELECT * the WHERE ID = Users the FROM 10;

  Scan can be used to select the results of the scan structure (named or to match)

type Result struct {
    Name string
    Age  int
}
var result Result
db.Table("users").Select("name, age").Where("name = ?", 3).Scan(&result)

  3)Update

 As long as you perform the update, update user

db.Save(&user)

Also update method, if the filter conditions (where), caught in the pre-update.

db.Model(&user).Update("name", "hello")

There are other ways to check the document update

Batch operations with updates

  

 

Guess you like

Origin www.cnblogs.com/GW977/p/11079218.html