trapping a MySql warning

前端 未结 7 1059
逝去的感伤
逝去的感伤 2020-11-29 23:59

In my python script I would like to trap a \"Data truncated for column \'xxx\'\" warning durnig my query using MySql.

I saw some posts suggesting the code below, but

7条回答
  •  时光说笑
    2020-11-30 00:22

    Warnings are just that: warnings. They get reported to (usually) stderr, but nothing else is done. You can't catch them like exceptions because they aren't being raised.

    You can, however, configure what to do with warnings, and turn them off or turn them into exceptions, using the warnings module. For instance, warnings.filterwarnings('error', category=MySQLdb.Warning) to turn MySQLdb.Warning warnings into exceptions (in which case they would be caught using your try/except) or 'ignore' to not show them at all. You can (and probably should) have more fine-grained filters than just the category.

提交回复
热议问题