当前位置:网站首页>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)
}
边栏推荐
猜你喜欢

“AI教练”请进家,家庭智能健身蓬勃发展

When does MySQL use table locks and when does it use row locks?

How to understand plucker coordinates (geometric understanding)

Pioneer in Distributed Systems - Leslie Lambert

AI can identify race from X-rays, but no one knows why

LVM和磁盘配额

Calculate the inverse source of the matrix (using the adjoint matrix, a 3x3 matrix)

Go语学习笔记 - gorm使用 - 数据库配置、表新增 Web框架Gin(七)

Detailed explanation of numpy multidimensional array ndarray

C#的访问修饰符,声明修饰符,关键字有哪些?扫盲篇
随机推荐
sql concat()函数
Detailed explanation of numpy multidimensional array ndarray
Mobile phone side scroll to page to specify location
Upload file -- file type, picture type, document type, video type, compressed package type
RAID disk array
go : 使用gorm查询记录
限塑令下的新材料——聚乳酸(PLA)
ETL为什么经常变成ELT甚至LET?
Ali: How many methods are there for multi-threaded sequential operation?
Rodrigues:旋转矩阵的向量表达
Proof of distance calculation from space vertex to plane and its source code
Calculate the inverse source of the matrix (using the adjoint matrix, a 3x3 matrix)
使用navicat连接mysql数据库时常报的错误:2003、1698、1251
阿里二面:列出 Api 接口优化的几个技巧
MySQL题外篇【ORM思想解析】
golang : Zap日志整合
schur completement
How does Redis prevent oversold and inventory deduction operations?
uniapp中canvas与v-if更“配”
云服务器零基础部署网站(保姆级教程)