Skip to content

3.创建

afumu edited this page Jun 6, 2023 · 1 revision

创建单条记录

user := User{Username: "afumu", Password: "123456", Age: 18}
  result := gplus.Insert(&user)
  fmt.Println(user.ID)             // 打印插入数据的主键
  fmt.Println(result.Error)        // 打印 error
  fmt.Println(result.RowsAffected) // 打印插入记录的条数
  //  INSERT INTO `users` (`username`,`password`,`address`,`age`,`phone`,`score`,`dept`,`created_at`,`updated_at`) VALUES ('afumu','123456','',18,'',0,'','2023-06-03 11:57:07.708','2023-06-03 11:57:07.708')

指定字段创建记录

  user := User{Username: "afumu", Password: "123456", Age: 18, Address: "北京", Score: 60}
  // 缓存模型字段指针,返回模型对象
  u := gplus.GetModel[User]()
  result := gplus.Insert(&user, gplus.Select(&u.Username, &u.Password))
  fmt.Println(user.ID)             // 打印插入数据的主键
  fmt.Println(result.Error)        // 打印 error
  fmt.Println(result.RowsAffected) // 打印插入记录的条数
  // INSERT INTO `users` (`username`,`password`,`created_at`,`updated_at`) VALUES ('afumu','123456','2023-06-03 12:05:10.532','2023-06-03 12:05:10.532')

注意:在上面指定插入字段中,我们并没有指定created_at和updated_at字段,这是gorm默认填充。

忽略字段创建记录

  user := User{Username: "afumu", Password: "123456", Age: 18, Address: "北京", Score: 60}
  // 缓存模型字段指针,返回模型对象
  u := gplus.GetModel[User]()
  result := gplus.Insert(&user, gplus.Omit(&u.Username, &u.Password))
  fmt.Println(user.ID)             // 打印插入数据的主键
  fmt.Println(result.Error)        // 打印 error
  fmt.Println(result.RowsAffected) // 打印插入记录的条数
  // INSERT INTO `users` (`address`,`age`,`phone`,`score`,`dept`,`created_at`,`updated_at`) VALUES ('北京',18,'',60,'','2023-06-03 12:08:40.357','2023-06-03 12:08:40.35)

批量插入

  user1 := User{Username: "afumu", Password: "123456", Age: 18, Address: "北京", Score: 60}
  user2 := User{Username: "afumu", Password: "123456", Age: 18, Address: "北京", Score: 60}
  users := []*User{&user1, &user2}
  result := gplus.InsertBatch(users)
  for _, user := range users {
    fmt.Println(user.ID) // 打印插入数据的主键
  }
  fmt.Println(result.Error)        // 打印 error
  fmt.Println(result.RowsAffected) // 打印插入记录的条数

指定分批数量插入

  user1 := User{Username: "afumu", Password: "123456", Age: 18, Address: "北京", Score: 60}
  user2 := User{Username: "afumu", Password: "123456", Age: 18, Address: "北京", Score: 60}
  user3 := User{Username: "afumu", Password: "123456", Age: 18, Address: "北京", Score: 60}
  users := []*User{&user1, &user2, &user3}
  result := gplus.InsertBatchSize(users, 2)
  for _, user := range users {
    fmt.Println(user.ID) // 打印插入数据的主键
  }
  fmt.Println(result.Error)        // 打印 error
  fmt.Println(result.RowsAffected) // 打印插入记录的条数
Clone this wiki locally