How to hide warning about drop table message to MariaDB

DL Neil PythonList at DancesWithMice.info
Sun Jan 19 16:18:05 EST 2020


On 20/01/20 4:35 AM, Python wrote:
> ^Bart wrote:
>> I ran this code:
>>
>> #!/usr/bin/python
>> import MySQLdb
>>
>> # Open database connection
>> db = MySQLdb.connect("localhost","root","MyPwd","MyDB")
>>
>> # prepare a cursor object using cursor() method
>> cursor = db.cursor()
>>
>> # Drop table if it already exist using execute() method.
>> cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
>>
>> # Create table as per requirement
>> sql = """CREATE TABLE EMPLOYEE (
>>           FIRST_NAME  CHAR(20) NOT NULL,
>>           LAST_NAME  CHAR(20),
>>           AGE INT,
>>           SEX CHAR(1),
>>           INCOME FLOAT )"""
>>
>> cursor.execute(sql)
>>
>> # disconnect from server
>> db.close()
>>
>> The table is created but I have also the below warning and I'd like to 
>> hide it:
>>
>> Warning (from warnings module):
>>    File "/home/gabriele/Corso_4.0/Python/MySQL_create_table.py", line 11
>>      cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
>> Warning: (1051, "Unknown table 'gabfood.EMPLOYEE'")
>>  >>>
> 
> import warnings
> 
> with warnings.catch_warnings():
>      warnings.simplefilter("ignore")
>      # your code


Recommend starting at the source (hah!) of the problem: MySQL!
(above includes (small!) risk of Python warnings becoming wrapped-up in 
what is actually a MySQL-specific  'problem')

NB I use the MySQL Connector/Python, downloaded from the MySQL Dev site 
(also source of useful manuals).
- intriguingly I've always understood the manuals to say that raising 
Warnings is False, ie suppressed; yet history shows that the behavior 
is/has always been (to my recollection) that Warnings are raised...
- similarly, we both seem to expect that if the SQL includes "IF EXISTS" 
we've already foreseen and wish to side-step the problem???


Option 1:
Amongst the connector's batteries-included are a bunch of Exception 
classes including "mysql.connector.errors.Warning". These enable queries 
to be wrapped in try-except blocks, eg:

try:
	cursor.execute(sql)
except MySQL_warning:
	# which could be more precise, as you desire
	# ie check tbl != exist, then pass


Option 2:
Please review the MySQL Connectors and APIs guide (or the Python-only 
version). You will find Section 7.5 "Connector/Python Coding Examples" 
illustrative. (there are also some (rather thin) tutorials - but better 
than nothing!). Section 7.9 "Connector/Python API Reference" offers 
additional MySQL 'commands' which you might use to suppress the Warning 
before it is raised.

-- 
Regards =dn


More information about the Python-list mailing list