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 it doesn' work.
Do you know if some specific module must be imported or if some option/flag should be called before using this code?
Thanks all
Afeg
import MySQLdb try: cursor.execute(some_statement) # code steps always here: No Warning is trapped # by the code below except MySQLdb.Warning, e: # handle warnings, if the cursor you're using raises them except Warning, e: # handle warnings, if the cursor you're using raises them
In the mysql client, you can enable and disable automatic warnings display using the warnings and nowarning commands, respectively, or their shortcuts, \W and \w (see Section 4.5.
To suppress warnings, set SQL_NOTES=0.
The \W command will show warnings after every statement, while \w will disable this. Starting the client with the --show-warnings option will show warnings after every statement. MariaDB 10.3.
Correct Option: B The SHOW WARNINGS command is used after executing one of those statements to see the warning messages.
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.
Raise MySQL Warnings as errors:
import warnings, MySQLdb warnings.filterwarnings('error', category=MySQLdb.Warning)
To ignore instead of raising an error, replace "error"
with "ignore"
.
Handle them in a try-except block like:
try: # a MySQL DB operation that raises a warning # for example: a data truncated warning except Warning as a_warning: # do something here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With