当前位置:网站首页>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)
}
边栏推荐
猜你喜欢
随机推荐
MySQL什么时候用表锁,什么时候用行锁?
Upload file -- file type, picture type, document type, video type, compressed package type
export , export default, import complete usage
什么是微服务?
Boot process and service control
Data types of Redis6
The CTO said I was not advised to use SELECT *, why is that?
Table with tens of millions of data, how to query the fastest?
B站崩了,如果是你是那晚负责的开发人员你会怎么做?
MYSQL下载及安装完整教程
使用navicat连接mysql数据库时常报的错误:2003、1698、1251
STL源码剖析:class template explicit specialization代码测试和理解
阿里一面:多线程顺序运行有多少种方法?
2020年度总结——品曾经,明得失,展未来
手机端滚动至页面指定位置
ETL为什么经常变成ELT甚至LET?
New breakthrough in artificial muscle smart materials
向量叉乘的几何意义及其模的计算
idea内置翻译插件
LVM and disk quotas









