后臺服務(wù)在運行時發(fā)現(xiàn)一個問題,運行約15分鐘后,接口請求報錯
pymysql.err.InterfaceError: (0, '')
這個錯誤提示一般發(fā)生在將None賦給多個值,定位問題時發(fā)現(xiàn)
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
如何解決這個問題呢
出現(xiàn)問題的代碼
class MysqlConnection(object): """ mysql操作類,對mysql數(shù)據(jù)庫進行增刪改查 """ def __init__(self, config): # Connect to the database self.connection = pymysql.connect(**config) self.cursor = self.connection.cursor() def Query(self, sql): """ 查詢數(shù)據(jù) :param sql: :return: """ self.cursor.execute(sql) return self.cursor.fetchall()
在分析問題前,先看看Python 數(shù)據(jù)庫的Connection、Cursor兩大對象
Python 數(shù)據(jù)庫圖解流程
Connection、Cursor形象比喻
Connection()的參數(shù)列表
- host,連接的數(shù)據(jù)庫服務(wù)器主機名,默認為本地主機(localhost)
- user,連接數(shù)據(jù)庫的用戶名,默認為當前用戶
- passwd,連接密碼,沒有默認值
- db,連接的數(shù)據(jù)庫名,沒有默認值
- conv,將文字映射到Python類型的字典
- cursorclass,cursor()使用的種類,默認值為MySQLdb.cursors.Cursor
- compress,啟用協(xié)議壓縮功能
- named_pipe,在windows中,與一個命名管道相連接
- init_command,一旦連接建立,就為數(shù)據(jù)庫服務(wù)器指定一條語句來運行
- read_default_file,使用指定的MySQL配置文件
- read_default_group,讀取的默認組
- unix_socket,在unix中,連接使用的套接字,默認使用TCP
-
port,指定數(shù)據(jù)庫服務(wù)器的連接端口,默認是3306
connection對象支持的方法
Cursor對象支持的方法
用于執(zhí)行查詢和獲取結(jié)果
execute方法:執(zhí)行SQL,將結(jié)果從數(shù)據(jù)庫獲取到客戶端
調(diào)試代碼,將超時時間設(shè)置較長
self.connection._write_timeout = 10000
發(fā)現(xiàn)并沒有生效
使用
try...except...
方法捕獲失敗后重新連接數(shù)據(jù)庫
try: self.cursor.execute(sql) except: self.connection() self.cursor.execute(sql)
直接拋出異常,并沒有執(zhí)行except代碼段
打印
self.connection
,輸出如下:
拋出異常重新connect是不行的,因為
connections
仍存在未失效
找到一種方法可以解決問題,在每次連接之前,判斷該鏈接是否有效,pymysql提供的接口是
Connection.ping()
這個該方法的源碼
def ping(self, reconnect=True): """Check if the server is alive""" if self._sock is None: if reconnect: self.connect() reconnect = False else: raise err.Error("Already closed") try: self._execute_command(COMMAND.COM_PING, "") return self._read_ok_packet() except Exception: if reconnect: self.connect() return self.ping(False) else: raise
在每次請求數(shù)據(jù)庫前執(zhí)行如下代碼
def reConnect(self): try: self.connection.ping() except: self.connection()
不過這樣的方式雖然能解決問題,但是感覺相對較low,希望有更好的處理方法
目前已實現(xiàn)的數(shù)據(jù)庫查詢這部分的代碼
import pymysql class DBManager(object): def __init__(self,config): self.connection = pymysql.connect(**config) # config為數(shù)據(jù)庫登錄驗證配置信息 self.cursor = self.connection.cursor() def query(self, sql, params): try: with self.connection.cursor() as cursor: cursor.execute(sql, params) result = cursor.fetchall() self.connection.commit() return result # self.connection.close() except Exception as e: traceback.print_exc()
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
