【问题标题】:How to insert data to SQLServer with GORM by using *DB.Create()如何使用 *DB.Create() 使用 GORM 将数据插入 SQLServer
【发布时间】:2020-11-24 05:55:53
【问题描述】:

我找到了两种使用 GORM 将数据插入 SQLServer 的方法。

  1. GORM.DB.Exec("insert into [tableA] (value1,value2) VALUES (?,?)",v1,v2)。它有效。
  2. GROM.DB.Create(&myDataStruct).Error。这会报告错误并且消息是“不支持 LastInsertId。请使用 OUTPUT 子句或在查询末尾添加 select ID = convert(bigint, SCOPE_IDENTITY())。”

我明白这条指令的含义是什么,但我不知道如何编码。 感谢您的帮助。

按照我的代码

db := mssql.GetMssqlDB()
    defer db.Close()

    newData := mssql.People{
        Name: "Tom",
        Age:  12,
    }
    err := db.Create(&newData).Error
    if err != nil {
        fmt.Println()
    }

和数据结构


type People struct {
    ID   int64  `gorm:"primary_key;column:id"`
    Name string `gorm:"column:name"`
    Age  int    `gorm:"column:age"`
}

func (p People) TableName() string {
    return "dbo.people"
}

【问题讨论】:

    标签: sql-server go insert go-gorm


    【解决方案1】:

    这是一个错误,自https://github.com/go-gorm/gorm/pull/2690 以来已修复。 如果您遇到同样的错误,请尝试更新您的 gorm,它应该可以工作。

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 2021-12-20
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      相关资源
      最近更新 更多