Insert data

4.Insert data

You can insert objects to database via Insert method.

  • Insert one object
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 objects 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 two objects onto two tables.
user := new(User)
user.Name = "myname"
question := new(Question)
question.Content = "whywhywhwy?"
affected, err := engine.Insert(user, question)
  • Insert multiple objects 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 objects 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.