One - One Code All

Blog Content

pymysql.err.InterfaceError: (0, '')解决办法db.ping(reconnect=True)

Python   2017-09-21 18:44:24

导致这个错误的原因是通过pymysql连接MySQL,没有关闭连接的操作,所以短时间内不会出问题,长时间保持这个连接会出现连接混乱。虽然看着自己的代码没错,还是会报


pymysql.err.InterfaceError: (0, '')错误。所以这个连接要么连上之后,用完就关闭。要么就用下面的代码,检查连接是否存在,断开的话会重连。

db = pymysql.connect(host='127.0.0.1',port=3306,user='user', passwd='pwd', db='db_name', charset='utf8')
sql = 'select * from table_name'
db.ping(reconnect=True)
cur.execute(sql)
db.commit()

实例:

def select_db(self, sql):
   """查询"""
   # 检查连接是否断开,如果断开就进行重连
   self.conn.ping(reconnect=True)
   # 使用 execute() 执行sql
   self.cur.execute(sql)
   # 使用 fetchall() 获取查询结果
   data = self.cur.fetchall()
   return data

def execute_db(self, sql):
   """更新/新增/删除"""
   try:
       # 检查连接是否断开,如果断开就进行重连
       self.conn.ping(reconnect=True)
       # 使用 execute() 执行sql
       self.cur.execute(sql)
       # 提交事务
       self.conn.commit()
   except Exception as e:
       print("操作出现错误:{}".format(e))
       # 回滚所有更改
       self.conn.rollback()


上一篇:python格式化字符串f-string
下一篇:NLP之中文近义词工具包Synonyms

The minute you think of giving up, think of the reason why you held on so long.