Force mysql to throw error if no rows deleted (trying to delete non-existent row)

两盒软妹~` 提交于 2020-06-13 06:03:29

问题


I am using Perl DBI (execute_array), but I think that this is more of a mysql issue.

I am trying to DELETE a few rows, and ran into the issue that the command completes successfully with no errors, but my rows are not being deleted (modified rows returns 0E0, i.e., "zero but true", i.e., "0 rows deleted"). When I tried via PHPMyAdmin, the rows deleted with no issue. After some debugging and long blank stares at my screen, I realized that one of the columns I was using in my DELETE statement had been truncated when added, which explained why the row could not be found by my script, but PHPMyAdmin had no problems with it. However, this did not explain why I was not getting any errors.

So, I guess this is by design, but am wondering if there is a way to get mysql to raise an error when you try to delete something that is not there. I know I can check to see if the number of affected rows is the same as the number of tuples supplied, but this does not tell me which rows were successfully removed, and which tuples referred to non-existent rows (since I am using execute_array for this very purpose). Any ideas?


回答1:


I found a workaround for my specific use-case, and am posting as an answer in case it is useful for someone else out there.

In the return for execute_array

$sth->execute_array( { ArrayTupleStatus => \@return_vector } )

It actually returns a "rows modified" value per row (when successful; when it fails the result is an array ref), so though it is not really an error, I can just check whether each given tuple execution modified non-zero rows (you need to use == not eq though, since the return is '0E0').

if (ref $return_vector[$i])
    { print "DELETE failed, reason: $return_vector[$i][1]"; }
elsif ($return_vector[$i] == 0)
    { print "DELETE failed, no rows matched tuples"; }
else
    { print "DELETE successful"; }


来源:https://stackoverflow.com/questions/37774569/force-mysql-to-throw-error-if-no-rows-deleted-trying-to-delete-non-existent-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!