Search code examples
mysqlclibmysql

How to get mysql to throw an error on update for no rows matched?


I want to know when an UPDATE query reports 0 rows matches. I'm using libmysql.

Here's the code I'm using:

char query[300] = {0};
snprintf(query, 300, "UPDATE `my_table` SET name='%s' WHERE id=%d",
         name, id);

if (mysql_query(db, query)) {
    printf("Error!\n");
}

Essentially what I need to know is whether or not there is a match for id. I know I can check that by doing a select, but is there another way?


Solution

  • Check mysql_affected_rows. This will return number of modified rows by the last query.

    However, it may return just the rows actually modified. If you want to return matched row, you have to specify CLIENT_FOUND_ROWS in mysql_real_connect. Check the same page for details.