更新时间:2024-10-23 GMT+08:00
分享

gorm

创建gorm.io/gorm包gorm.DB数据源,进行mysql操作

依赖引入,配置文件或配置信息修改参考原生DB

初始化创建gorm数据源DevSporeGorm,后续执行Mysql相关操作。

  • 配置文件方式创建。
    import (
        "log"
    
        _ "github.com/huaweicloud/devcloud-go/sql-driver/mysql"
        "gorm.io/driver/mysql"
        "gorm.io/gorm"
    )
    var (
        DevSporeGorm *gorm.DB
        err error
    )
    func init() {
        DevSporeGorm, err = gorm.Open(mysql.New(
          mysql.Config{DriverName: "devspore_mysql", DSN: "./conf/resources/config_mysql.yaml"},
        ))
        if err != nil {
            log.Fatalln(err)
        }
    }
  • 配置信息方式创建。
    import (
        "log"
    
        devspore "github.com/huaweicloud/devcloud-go/sql-driver/mysql"
        "gorm.io/driver/mysql"
        "gorm.io/gorm"
    )
    var (
        DevSporeGorm *gorm.DB
        err error
    )
    func init() {
        devspore.SetClusterConfiguration(mysqlConfiguration())
        DevSporeGorm, err = gorm.Open(mysql.New(mysql.Config{DriverName: "devspore_mysql", DSN: ""}))
        if err != nil {
            log.Fatalln(err)
        }
    }

相关文档