skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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
    }
    

    1. gormDB.Raw() will return (tx *DB), it would not execute,
      generally, it use to query.
    2. use directly gormDB.exec()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search