Documentation Home
MySQL 8.0 C API Developer Guide
Download this Manual
PDF (US Ltr) - 1.3Mb
PDF (A4) - 1.3Mb


5.4.1 mysql_affected_rows()

uint64_tmysql_affected_rows(MYSQL *mysql)

Description

mysql_affected_rows() may be called immediately after executing a statement withmysql_real_query() ormysql_query(). It returns the number of rows changed, deleted, or inserted by the last statement if it was anUPDATE,DELETE, orINSERT. ForSELECT statements,mysql_affected_rows() works likemysql_num_rows().

ForUPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify theCLIENT_FOUND_ROWS flag tomysql_real_connect() when connecting tomysqld, the affected-rows value is the number of rowsfound; that is, matched by theWHERE clause.

ForREPLACE statements, the affected-rows value is 2 if the new row replaced an old row, because in this case, one row was inserted after the duplicate was deleted.

ForINSERT ... ON DUPLICATE KEY UPDATE statements, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWS flag, the affected-rows value is 1 (not 0) if an existing row is set to its current values.

Following aCALL statement for a stored procedure,mysql_affected_rows() returns the value that it would return for the last statement executed within the procedure, or0 if that statement would return-1. Within the procedure, you can useROW_COUNT() at the SQL level to obtain the affected-rows value for individual statements.

mysql_affected_rows() returns a meaningful value for a wide range of statements. For details, see the description forROW_COUNT() inInformation Functions.

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for anUPDATE statement, no rows matched theWHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error or that, for aSELECT query,mysql_affected_rows() was called prior to callingmysql_store_result().

Becausemysql_affected_rows() returns an unsigned value, you can check for -1 by comparing the return value to(uint64_t)-1 (or to(uint64_t)~0, which is equivalent).

Errors

None.

Example

char *stmt = "UPDATE products SET cost=cost*1.25              WHERE group=10";mysql_query(&mysql,stmt);printf("%ld products updated",       (long) mysql_affected_rows(&mysql));