python mysql斷開重連的實現(xiàn)方法
后臺服務(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
,輸出如下:
<pymysql.connections.Connection object at 0x0000000003E2CCC0>
拋出異常重新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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實現(xiàn)linux服務(wù)器批量修改密碼并生成execl
這篇文章主要介紹了python實現(xiàn)linux服務(wù)器批量修改密碼并生成execl示例,需要的朋友可以參考下2014-04-04python中的iterator和"lazy?iterator"區(qū)別介紹
這篇文章主要介紹了python中的iterator和?“l(fā)azy?iterator“之間有什么區(qū)別,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04詳解pyppeteer(python版puppeteer)基本使用
這篇文章主要介紹了詳解pyppeteer(python版puppeteer)基本使用 ,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06python字符串,元組,列表,字典互轉(zhuǎn)代碼實例詳解
這篇文章主要介紹了python字符串,元組,列表,字典互轉(zhuǎn)代碼實例詳解,需要的朋友可以參考下2020-02-02python3+PyQt5 數(shù)據(jù)庫編程--增刪改實例
今天小編就為大家分享一篇python3+PyQt5 數(shù)據(jù)庫編程--增刪改實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06