• gorm 之数据插入(转)


    转自:gorm 之数据插入

    1.全字段属性插入

    Creat结构体全字段属性插入

    package main
    
    import (
    	"fmt"
    	"gorm.io/driver/mysql"
    	"gorm.io/gorm"
    )
    
    //模型结构
    type Student struct {
    	Id   int
    	Name string
    	Age  int
    }
    
    func main() {
    	//使用dsn连接到数据库,grom自带的数据库池
    	//账号:密码@连接方式(ip地址:端口号)/数据库?语言方式,时区(未设置时区的话采用8小时制度)
    	dsn := "root:414524@tcp(127.0.0.1:3306)/gotest?charset=utf8mb4&parseTime=True&loc=Local"
    	conn, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) //使用mysq连接数据库,第二个参数可以增加更多的配置(可有可无)
    	if err != nil {
    		fmt.Println(err)
    	}
    	conn.AutoMigrate(&Student{}) //创建表?判断是否表结构存在
    
    	stu := &Student{
    		Id:   1,
    		Name: "yang",
    		Age:  22,
    	}
    	res := conn.Create(stu) //向数据库中插入数据  ,它的返回值只有一个类型,没有error类型
    	//注:如果上面写成stu := Student{...},则这里写成Create(&stu) 
    
    	if res.Error != nil {   //判断是否插入数据出错
    		fmt.Println(res.Error)
    	}
    }
    //控制台点击运行后控制台不会有任何输出
    

    2.部分字段属性插入

    Select结构体部分字段属性插入

    stu := &Student{
        Id: 2,
        Name: "xin",
    }
    res := conn.Select("Id","Name").Create(stu)
    

    3.批量插入

    Creat批量插入

    stu := []Student{
    	{Name: "jun", Age: 24},
    	{Name: "zhou", Age: 26},
    }
      
    conn.Create(&stu)//传入stu的地址
    

    转自:gorm 之数据插入

  • 相关阅读:
    程序编译与代码优化 -- 早期(编译期)优化
    Java字节码指令
    知识点
    Openresty配置文件上传下载
    Openresty + nginx-upload-module支持文件上传
    G1日志分析
    Garbage First(G1)垃圾收集器
    Java内存分析工具jmap
    编译JDK1.7
    Java服务CPU占用高问题定位方法
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/16440128.html
Copyright © 2020-2023  润新知