How do I get the number of affected rows when I use DBI's prepare/execute for non-select statement?

new_perl picture new_perl · Aug 3, 2011 · Viewed 10.8k times · Source

According to the DBI documentation, it seems I can only get the number of affected rows by the do method.

$rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");

How can I get the same result if I use prepare/execute?

Answer

e.dan picture e.dan · Aug 3, 2011

From the documentation about the execute method in DBI:

For a non-"SELECT" statement, "execute" returns the number of rows affected, if known. If no rows were affected, then "execute" returns "0E0", which Perl will treat as 0 but will regard as true. Note that it is not an error for no rows to be affected by a statement. If the number of rows affected is not known, then "execute" returns -1.