简体   繁体   English

GORM 原始 sql 未执行

[英]GORM Raw sql not getting executed

I have a simple UPDATE SQL statement that I am trying to execute:我有一个简单的 UPDATE SQL 语句,我正在尝试执行:

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.没有记录任何内容,也没有保留任何数据库更改。

Calling Raw by itself does not execute the query.单独调用Raw不会执行查询。 One way to execute the operation and to retrieve the results is using the Rows() method:执行操作和检索结果的一种方法是使用Rows()方法:

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:然而,在我的例子中,我不需要访问返回的结果,所以我选择使用Exec方法,它会立即执行给定的 SQL:

if err := gormDB.Exec("UPDATE orders SET item_id = ? WHERE client_id = ?", "item1", "client1").Error; err != nil {
    return err
}
  1. gormDB.Raw() will return (tx *DB), it would not execute, generally, it use to query. gormDB.Raw() 将返回 (tx *DB),它不会执行,一般用于查询。
  2. use directly gormDB.exec()直接使用 gormDB.exec()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM