GORM Insert Data

From WikiOD

One, gorm new record[edit | edit source]

//Define a user and initialize the data
u := User{

//Insert a user data
//The following code will automatically generate SQL statements: INSERT INTO `users` (`username`,`password`,`createtime`) VALUES ('wikiod','123456','1540824823')


//In the general project, we will look similar to the following, through the error object detection, inserting data is successful, if there is no error, the data is successful.
if err := db.Create(u).Error; err != nil {
    fmt.Println("Insert failure", err)

2. How does gorm obtain the auto-incremented Id of the newly inserted record[edit | edit source]

The gorm library does not automatically return the id of the newly inserted record by default, and we need to process it ourselves. We want to get the auto-increment Id of the newly inserted data, essentially through the SQL statement : SELECT LAST_INSERT_ID() to  get the auto-increment id of the last insert statement

Then the steps to get the auto-increment id after gorm adds a record are as follows:

  1. Use db.Create to insert records
  2. Execute sql statement SELECT LAST_INSERT_ID() to obtain Id

Example code:

//Define a user and initialize the data
u := User{...Ignore the initialization code...} 
//Insert record
//Get the ID of the recorded record
var id []int
db.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)

//Because the PLUCK function returns a column value, the return result is the slice type, and we have only one value here, so take the first value.

Tip: If gorm sets up a database connection pool, then every time a database query is executed, it will apply for a database connection from the database connection pool. Then the above code must use database transactions to ensure that the two sql statements for inserting data and querying auto-increment id are in Execute under the same database connection. Otherwise, in high concurrency scenarios, the auto-increment id may not be queried, or the wrong id may be queried.