Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trapping a MySql warning

Tags:

python

mysql

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 
like image 397
Abruzzo Forte e Gentile Avatar asked Jan 20 '10 14:01

Abruzzo Forte e Gentile


People also ask

How do I enable show warnings in mysql?

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.

How do I turn off mysql warnings?

To suppress warnings, set SQL_NOTES=0.

How do I show warning in MariaDB?

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.

What is the command to see warning messages?

Correct Option: B The SHOW WARNINGS command is used after executing one of those statements to see the warning messages.


2 Answers

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.

like image 155
Thomas Wouters Avatar answered Sep 23 '22 14:09

Thomas Wouters


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 
like image 40
Rakib Avatar answered Sep 24 '22 14:09

Rakib