当前位置:网站首页>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)
}
边栏推荐
- The CTO said I was not advised to use SELECT *, why is that?
- 头条二面:MySQL中有几种常见的 SQL 错误用法?
- Calculate the inverse source of the matrix (using the adjoint matrix, a 3x3 matrix)
- Required request body is missing problem solving
- 《心智社会》—马文·明斯基
- 计算矩阵的逆源码(使用伴随矩阵,3×3的矩阵)
- New breakthrough in artificial muscle smart materials
- 人工肌肉智能材料新突破
- What happens when @Bean and @Component are used on the same class?
- How to understand plucker coordinates (geometric understanding)
猜你喜欢
随机推荐
Oracle查看表空间使用率及爆满解决方案
When does MySQL use table locks and when does it use row locks?
The calculation and source code of the straight line intersecting the space plane
The CTO said I was not advised to use SELECT *, why is that?
export , export default,import完整用法
限塑令下的新材料——聚乳酸(PLA)
让百度地图生成器里的“标注”内容展开--解决方案
2020 数学建模之旅
AI可通过X光片识别种族,但没人知道为什么
golang : Zap日志整合
Process and Scheduled Task Management
What happens when @Bean and @Component are used on the same class?
MySQL什么时候用表锁,什么时候用行锁?
这个终端连接工具,碾压Xshell
DHCP principle and configuration
向量叉乘的几何意义及其模的计算
阿里二面:Sentinel vs Hystrix 对比,如何选择?
向量三重积的等式推导证明
从追赶到超越,国产软件大显身手
使用navicat连接mysql数据库时常报的错误:2003、1698、1251









