mysql重連次數 MySQL 重連機制

2021-10-17 22:16:37 字數 1860 閱讀 4113

#!/usr/bin/env python#-*-coding:utf-8-*-

importsys, mysqldb, tracebackimporttimeclassmysql:def __init__(self,

host='',

user='',

passwd='',

db='',

port=3306,

charset='utf8'):

self.host=host

self.user=user

self.passwd=passwd

self.db=db

self.port=port

self.charset=charset

self.conn=none

self._conn()def_conn(self):try:

self.conn=mysqldb.connection(self.host, self.user, self.passwd, self.db, self.port, self.charset)returntrueexcept:returnfalsedef _reconn(self, num=28800, stime=3): #重試連線總次數為1天,這裡根據實際情況自己設定,如果伺服器宕機1天都沒發現就......

_number =0

_status=truewhile _status and _number <=num:try:

self.conn.ping()#cping 校驗連線是否異常

_status =falseexcept:if self._conn() == true: #重新連線,成功退出

_status =falsebreak_number+= 1time.sleep(stime)#連線不成功,休眠3秒鐘,繼續迴圈,知道成功或重試次數結束

def select(self, sql=''):try:

self._reconn()

self.cursor=self.conn.cursor(mysqldb.cursors.dictcursor)

self.cursor.execute(sql)

result=self.cursor.fetchall()

self.cursor.close()returnresultexceptmysqldb.error, e:#print "error %d: %s" % (e.args[0], e.args[1])

returnfalsedef select_limit(self, sql='', offset=0, length=20):

sql= '%s limit %d , %d ;' %(sql, offset, length)returnself.select(sql)def query(self, sql=''):try:

self._reconn()

self.cursor=self.conn.cursor(mysqldb.cursors.dictcursor)

self.cursor.execute("set names utf8") #utf8 字符集

result =self.cursor.execute(sql)

self.conn.commit()

self.cursor.close()return(true, result)exceptmysqldb.error, e:returnfalsedefclose(self):

self.conn.close()if __name__ == '__main__':

my= mysql('localhost', 'root', 'root', 'test', 3306)print my.select_limit('select * from a_table', 1, 1)#my.close()

mysql斷線重連 mysql斷線重連報錯

原本 dispatch by order 迴圈中,socket.block 方法是掛起協程阻塞的,當客戶端socket主動斷開的時候,socket 協程被喚醒發現 connected 為 false,繼續執行了 close channel socket self 和 wakeup all self ...

解決mysql自動重連

方法 1 連線mysql的語句寫上autoreconnect true 不過這是針對mysql版本是5以前的。重連的實現機制 方法 2 由於mysql資料庫的配置,引起的mysql等待連線時間 wait timeout 預設為8小時 28800s 設定interactive timeout和wait...

mysql的8小時重連問題

如果你沒有修改過mysql的配置,預設情況下,wait timeout 的初始值是28800。wait timeout 過大有弊端,其體現就是mysql裡大量的sleep程序無法及時釋放,拖累系統效能,不過也不能把這個指設定的過小,否則你可能會遭遇到 mysql has gone away 之類的問...