Python和MySQLdb-使用DROP TABLE IF EXISTS似乎会引发异常 [英] Python and MySQLdb - Using DROP TABLE IF EXISTS seems to throw exception
本文介绍了Python和MySQLdb-使用DROP TABLE IF EXISTS似乎会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到了此代码.
.....
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?
推荐答案
这是完全正确的行为.如果该表存在,则将其删除.如果它不存在,那么您会得到警告异常,该异常与 Error 不同-您可以随意忽略它,也不会发生任何不良情况,但是您必须抓住它可以让您的脚本继续执行.
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.
要防止警告冒泡,只需将其作为其他任何异常捕获即可:
To prevent Warning from bubbling up, just catch it as any other exception:
try:
[some code]
except MySQLdb.Warning:
[exception handling code]
这篇关于Python和MySQLdb-使用DROP TABLE IF EXISTS似乎会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文