英文:
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
- gormDB.Raw()会返回(tx *DB),它不会执行,通常用于查询。
- 直接使用gormDB.exec()。
英文:
- gormDB.Raw() will return (tx *DB), it would not execute,
generally, it use to query. - use directly gormDB.exec()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论