4.Insert data

Inserting records use Insert method.

  • Insert one record
user := new(User)
user.Name = "myname"
affected, err := engine.Insert(user)

After inserted, user.Id will be filled if Id is an autoincremented column.

fmt.Println(user.Id)
  • Insert multiple records by Slice on one table
users := make([]User, 1)
users[0].Name = "name0"
...
affected, err := engine.Insert(&users)
  • Insert multiple records by Slice of pointer on one table
users := make([]*User, 1)
users[0] = new(User)
users[0].Name = "name0"
...
affected, err := engine.Insert(&users)
  • Insert one record on two table.
user := new(User)
user.Name = "myname"
question := new(Question)
question.Content = "whywhywhwy?"
affected, err := engine.Insert(user, question)
  • Insert multiple records on multiple tables.
users := make([]User, 1)
users[0].Name = "name0"
...
questions := make([]Question, 1)
questions[0].Content = "whywhywhwy?"
affected, err := engine.Insert(&users, &questions)
  • Insert one or multple records on multiple tables.
user := new(User)
user.Name = "myname"
...
questions := make([]Question, 1)
questions[0].Content = "whywhywhwy?"
affected, err := engine.Insert(user, &questions)

Notice: If you want to use transaction on inserting, you should use session.Begin() before calling Insert.