python pymysql 报错 pymysql.err.InterfaceError: (0, ”) 或 AttributeError: ‘dict’ object has no attribute ‘Exception’

【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】
因为个人一直秉承着最好用最新版的原则,所以一直在使用Python3,结果今天在使用pymysql这个库,然后自己封装了一个mysql的类,但是各种报错。错误如下图:
当时自己百度了很多资料,基本都没解决问题。先给大家看我封装的类的代码吧。如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # -*-coding:utf-8-*-
import pymysql.cursors
class MysqlPool:
def __init__(self, dbname, username, password, host='127.0.0.1', port=3306, charset='utf8'):
self.pool = pymysql.connect(host=host, user=username, password=password, database=dbname, port=port,
charset=charset,cursorclass=pymysql.cursors.DictCursor)
def select_count(self, sql, sql_args=None):
try:
num = ""
with self.pool.cursor() as cursor:
cursor.execute(sql, sql_args)
result = cursor.fetchall()
if isinstance(result[0],dict):
num = result[0]["count(*)"]
elif isinstance(result[0],list):
num = result[0][0]
return num
except Exception as e:
print('select_count error: %s' % e)
return False
finally:
self.pool.close()
####后面的代码我就省略了。 |
当这个类写好后,因为我用的是flask框架,所以当程序启动后,第一次调用select_count的时候,数据返回正常,但是当第二次请求的时候,就会报错,出现pymysql.err.InterfaceError: (0, '') 和 AttributeError: 'dict' object has no attribute 'Exception'
_mysql.connection.query(self, query) _mysql_exceptions.interfaceerror: (0, '')
peewee.interfaceerror: (0, '')
dbconnectionerror pymysql err interfaceerror 0
pymysql error handling
interfaceerror (- 1 error totally whack ')
operational error in python
_mysql_exceptions dataerror
raise errorclass errno errval的错误,当时百思不得其解。因为代码明明是按照官网https://pymysql.readthedocs.io/en/latest/user/examples.html 写的, 后来说了一句,最后每次都会执行 self.pool.close() 会关闭Mysql连接池,这样就会关掉整个连接,当时思路就瞬间同了,因为使用了 with self.pool.cursor() as cursor ,所以也就不需要关闭每次的连接了,就和 with open("xxx/xxx.txt") as f 道理是一样的,当你用with open 的时候就不用close了,因为当时一直想的你连接了就需要关闭,省内存,所以没注意这个细节。所以只需要把 finally: self.pool.close() 这两个代码删掉就可以了。
下面是更改后的代码,这样就不会报错了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | # -*-coding:utf-8-*-
import pymysql.cursors
class MysqlPool:
def __init__(self, dbname, username, password, host='127.0.0.1', port=3306, charset='utf8'):
self.pool = pymysql.connect(host=host, user=username, password=password, database=dbname, port=port,
charset=charset,cursorclass=pymysql.cursors.DictCursor)
def select_count(self, sql, sql_args=None):
try:
num = ""
with self.pool.cursor() as cursor:
cursor.execute(sql, sql_args)
result = cursor.fetchall()
if isinstance(result[0],dict):
num = result[0]["count(*)"]
elif isinstance(result[0],list):
num = result[0][0]
return num
except Exception as e:
print('select_count error: %s' % e)
return False
####后面的代码我就省略了。 |
其实报这个错误的主要原因就是你的mysql 连接让你自己给关闭导致的。

布施恩德可便相知重
微信扫一扫打赏
支付宝扫一扫打赏