Python and MySQLdb - Using DROP TABLE IF EXISTS se

2020-07-10 03:21发布

I got this code..

.....
try:
    task_db.cursor.execute('DROP TABLE IF EXISTS `tasks`')
    print "Affected: %d" % task_db.cursor.rowcount 
except MySQLdb.Error, e:
    print "Error ocurred: %s " % e.args[0]
    print e

If the tasks table doesn't exist, then I get a warning like

create_database.py:11: Warning: Unknown table 'tasks'

But if the table does exist then I wont get that warning. Odd?

标签: python mysql
3条回答
够拽才男人
2楼-- · 2020-07-10 03:38

Catching the MySQLdb.Warning didn't work for me, so I found another way to suppress warnings:

import warnings
warnings.filterwarnings("ignore", "Unknown table.*")

And you can edit the second parameter with whatever you want to suppress.

查看更多
家丑人穷心不美
3楼-- · 2020-07-10 03:40

The most elegant way to avoid Mysql warnings :

from warnings import filterwarnings
import MySQLdb

filterwarnings('ignore', category = MySQLdb.Warning)
查看更多
Melony?
4楼-- · 2020-07-10 03:57

It's perfectly correct behaviour. If the table exists, then it's dropped. If it doesn't exist then you get Warning exception which is not the same as Error - you are free to ignore it and nothing bad should happen, but you have to catch it to allow your script to proceed.

EDIT:

To prevent Warning from bubbling up, just catch it as any other exception:

try:
    [some code]
except MySQLdb.Warning:
    [exception handling code]
查看更多
登录 后发表回答