GORM原始SQL未执行。

huangapple go评论85阅读模式
英文:

GORM Raw sql not getting executed

问题

我有一个简单的UPDATE SQL语句,我正在尝试执行:

if err := gormDB.Raw("UPDATE orders SET item_id = ? WHERE client_id = ?", "item1", "client1").Error; err != nil {
    return err
}

没有返回任何错误,但是我的查询似乎没有在数据库上执行。没有记录任何日志,也没有持久化任何数据库更改。

英文:

I have a simple UPDATE SQL statement that I am trying to execute:

if err := gormDB.Raw("UPDATE orders SET item_id = ? WHERE client_id = ?", "item1", "client1").Error; err != nil {
    return err
}

No errors are being returned, but my query is seemingly not being executed on the database. Nothing is logged, and no database changes are persisted.

答案1

得分: 3

调用Raw本身不会执行查询。执行操作并检索结果的一种方法是使用Rows()方法:

if _, err := gormDB.Raw("UPDATE orders SET item_id = ? WHERE client_id = ?", "item1", "client1").Rows(); err != nil {
    return err
}
// 解析结果...

然而,在我的情况下,我不需要访问返回的结果,所以我选择使用Exec方法,它会立即执行给定的SQL语句:

if err := gormDB.Exec("UPDATE orders SET item_id = ? WHERE client_id = ?", "item1", "client1").Error; err != nil {
    return err
}
英文:

Calling Raw by itself does not execute the query. One way to execute the operation and to retrieve the results is using the Rows() method:

if _, err := gormDB.Raw("UPDATE orders SET item_id = ? WHERE client_id = ?", "item1", "client1").Rows(); err != nil {
    return err
}
// Parse rows...

In my case however, I did not need to access the returned result, so I opted to use the Exec method, which immediately executes the given SQL:

if err := gormDB.Exec("UPDATE orders SET item_id = ? WHERE client_id = ?", "item1", "client1").Error; err != nil {
    return err
}

答案2

得分: 1

  1. gormDB.Raw()会返回(tx *DB),它不会执行,通常用于查询。
  2. 直接使用gormDB.exec()。
英文:
  1. gormDB.Raw() will return (tx *DB), it would not execute,
    generally, it use to query.
  2. use directly gormDB.exec()

huangapple
  • 本文由 发表于 2022年8月23日 06:40:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/73451662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定