当前位置:网站首页>go : 使用gorm创建数据库记录
go : 使用gorm创建数据库记录
2022-07-30 05:51:00 【行人已】
不要因为没有掌声而放弃梦想,你需要的是坚持而不是观众!!!
代码已放在: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)
}
边栏推荐
- STL源码剖析:bound friend template friend代码测试和理解
- idea内置翻译插件
- Selenium01
- DNS domain name resolution services
- UDP和TCP使用同一个端口,可行吗?
- ETL为什么经常变成ELT甚至LET?
- 2020 数学建模之旅
- 向量叉乘的几何意义及其模的计算
- Electron使用romote报错 : Uncaught TypeError: Cannot read property ‘BrowserWindow‘ of undefined
- AI can identify race from X-rays, but no one knows why
猜你喜欢
随机推荐
上传文件--文件类型大全,图片类型,文档类型,视频类型,压缩包类型
MYSQL下载及安装完整教程
window.open()的用法,js打开新窗体
Playing script killing with AI: actually more involved than me
STL源码剖析:临时对象的代码测试和理解
No, the Log4j vulnerability hasn't been fully fixed yet?
Electron日常学习笔记
The calculation proof of the intersection of the space line and the plane and its source code
redis实现分布式锁的原理
预测人们对你的第一印象,“AI颜狗”的诞生
限塑令下的新材料——聚乳酸(PLA)
[硬核干货]由0到1,突破信息系统项目管理师(呕心沥血经验之谈)!!!
Station B collapsed, what would you do if you were the developer in charge that night?
MongoDB - query
向量的导数运算和向量叉乘以及点乘的导数运算
LVM and disk quotas
(GGG)JWT
空间顶点到平面的距离计算的证明及其源码
bin文件夹下的roslyn文件夹
roslyn folder under bin folder









