Python 和 MySQLdb - 使用 DROP TABLE IF EXISTS 似乎抛出异常

7 投票
3 回答
11722 浏览
提问于 2025-04-16 06:50

我有这段代码……

.....
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

如果任务表不存在,我就会收到一个警告,内容是

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

但是如果这个表存在,我就不会收到这个警告。奇怪吧?

3 个回答

11

避免Mysql警告的最优雅方法:

from warnings import filterwarnings
import MySQLdb

filterwarnings('ignore', category = MySQLdb.Warning)
23

我尝试捕捉MySQLdb.Warning,但没成功,所以我找到了另一种方法来抑制警告:

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

你可以根据需要修改第二个参数,以抑制你想要的警告。

7

这个行为是完全正确的。如果表格存在,就会被删除。如果表格不存在,你会收到一个警告,这和错误是不一样的——你可以选择忽略这个警告,没什么大不了的,但你需要处理这个警告,这样你的脚本才能继续运行。

编辑:

为了防止警告影响后面的操作,只需像处理其他异常一样处理它:

try:
    [some code]
except MySQLdb.Warning:
    [exception handling code]

撰写回答