文章内容
2019/3/4 10:27:42,作 者: 黄兵
MySQLdb except 的捕捉方式
最近使用Python写的后台代码出了一点问题,在排查的时候,定位到数据存储存在异常,但是使用的是except方式,并没有看出来是哪里存在什么样的异常,导致排除异常很棘手。
具体代码如下:
try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback()
这样写,具体是什么异常,完全无法看出。之后参考了一下这篇文章:Error handling in Python-MySQL,修改异常的捕获,具体代码如下:
try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except (MySQLdb.Error, MySQLdb.Warning) as e: print(e) # 发生错误时回滚 db.rollback() return None
打印出具体的错误和警告内容,就可以很方便排查了。
TypeError: clean_counters() missing 1 required positional argument: 'self'
execute command denied to user
execute command denied to user
评论列表