当前位置:网站首页>go : create database records using gorm
go : create database records using gorm
2022-07-30 08:02:00 【pedestrians have】
不要因为没有掌声而放弃梦想,What you need is persistence, not an audience!!!
代码已放在:https://gitee.com/hjx_RuGuoYunZhiDao/strom-huang-go
可参照文档:https://learnku.com/docs/gorm/v2/create/9732#e9dfd9
1、 引入gorm
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
2、添加一个model
type TUser struct {
ID uint `gorm:"primaryKey"`
Name string
Password string
Phone string `gorm:"phone"`
NickName string `gorm:"nick_name"`
CreatedAt time.Time `gorm:"column:created_at;type:datetime"`
UpdatedAt time.Time `gorm:"column:updated_at;type:datetime"`
DeletedAt time.Time `gorm:"column:deleted_at;type:datetime"`
}
3、链接数据库
dsn := "root:[email protected](localhost:3306)/go_test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
4、创建数据
//普通创建
user := TUser{
Name: "test", Password: "123", NickName: "hello", Phone: "123", CreatedAt: time.Now()}
result := db.Create(&user) // 通过数据的指针来创建
fmt.Println(result.RowsAffected)
//创建记录并更新给出的字段
db.Select("name", "password", "phone", "nick_name").Create(&user)
//创建记录并更新未给出的字段
db.Omit("phone").Create(&user)
//批量插入 使用 CreateInBatches 创建时,你还可以指定创建的数量
var users = []TUser{
{
Name: "test1", Password: "123", NickName: "hello1", CreatedAt: time.Now()}, {
Name: "test2", Password: "123", NickName: "hello2", CreatedAt: time.Now()}}
db.Create(&users)
db.CreateInBatches(&users, 100)
5、具体代码:
package main
import (
"fmt"
"log"
"os"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
//model:
type TUser struct {
ID uint `gorm:"primaryKey"`
Name string
Password string
Phone string `gorm:"phone"`
NickName string `gorm:"nick_name"`
CreatedAt time.Time `gorm:"column:created_at;type:datetime"`
UpdatedAt time.Time `gorm:"column:updated_at;type:datetime"`
DeletedAt time.Time `gorm:"column:deleted_at;type:datetime"`
}
//指定数据库表名称
func (TUser) TableName() string {
return "t_user"
}
func main() {
//启用打印日志
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // Log level: Silent、Error、Warn、Info
Colorful: false, // 禁用彩色打印
},
)
dsn := "root:[email protected](127.0.0.1:3306)/go_admin?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
if err != nil {
fmt.Println(err)
return
}
//普通创建
user := TUser{
Name: "test", Password: "123", NickName: "hello", Phone: "123", CreatedAt: time.Now()}
result := db.Create(&user) // 通过数据的指针来创建
fmt.Println(result.RowsAffected)
//创建记录并更新给出的字段
db.Select("name", "password", "phone", "nick_name").Create(&user)
//创建记录并更新未给出的字段
db.Omit("phone").Create(&user)
//批量插入 使用 CreateInBatches 创建时,你还可以指定创建的数量
var users = []TUser{
{
Name: "test1", Password: "123", NickName: "hello1", CreatedAt: time.Now()}, {
Name: "test2", Password: "123", NickName: "hello2", CreatedAt: time.Now()}}
db.Create(&users)
db.CreateInBatches(&users, 100)
}
边栏推荐
猜你喜欢

Playing script killing with AI: actually more involved than me

图解关系数据库设计思想,这也太形象了

如何理解普吕克坐标(几何理解)

The calculation and source code of the straight line intersecting the space plane

Pioneer in Distributed Systems - Leslie Lambert

What happens when @Bean and @Component are used on the same class?

Distance calculation from space vertex to straight line and its source code

PXE efficient mass network capacity

和AI一起玩儿剧本杀:居然比我还入戏

uniapp中canvas与v-if更“配”
随机推荐
DHCP principle and configuration
The calculation proof of the intersection of the space line and the plane and its source code
Electron日常学习笔记
Redis 如何实现防止超卖和库存扣减操作?
手机端滚动至页面指定位置
Go 结合Gin导出Mysql数据到Excel表格
goto语句
node.js中实现对数据库的链式操作
@Bean 与 @Component 用在同一个类上,会怎样?
Pioneer in Distributed Systems - Leslie Lambert
go : 使用gorm查询记录
AI can identify race from X-rays, but no one knows why
人工肌肉智能材料新突破
如何理解普吕克坐标(几何理解)
使用navicat连接mysql数据库时常报的错误:2003、1698、1251
Ali Ermian: How many cluster solutions does Redis have?I answered 4
LVM和磁盘配额
Rodrigues:旋转矩阵的向量表达
LVM and disk quotas
The first artificial intelligence safety competition officially launched