python 長連接mysql實例

##起因
最近處理數據庫裏的數據,有餘數據太大,不可能採用短連接,只能採用長連接了。所以寫了個這個
參考資料
https://www.polarxiong.com/archives/Python-mysql-connector中獲取數據庫值的一些問題.html
https://blog.csdn.net/wzm112/article/details/7745835

from mysql import connector
import time

class mysql_connect:
    def __init__(self,
                 host='',
                 user='',
                 passwd='',
                 db='',
                 port=3306,
                 charset='utf8mb4'
                 ):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.db = db
        self.port = port
        self.charset = charset
        self.conn = None
        self.cursor = None
        self._conn()

    def _conn(self):
        try:
            self.conn = connector.connect(host=self.host,
                                          user=self.user,
                                          password=self.passwd,
                                          database=self.db,
                                          port=self.port)
            return True
        except:
            return False

    def _cursor(self):
        self.cursor = self.conn.cursor(dictionary=True)
        self.cursor.execute("set names '{}'".format(self.charset))

    def _free(self):
        self.cursor.close()

    def _reConn(self, num=28800, stime=3):  # 重試連接總次數爲1天,這裏根據實際情況自己設置,如果服務器宕機1天都沒發現就......
        _number = 0
        _status = True
        while _status and _number <= num:
            try:
                self.conn.ping()  # cping 校驗連接是否異常
                _status = False
            except:
                if self._conn() == True:  # 重新連接,成功退出
                    _status = False
                    break
                _number += 1
                time.sleep(stime)  # 連接不成功,休眠3秒鐘,繼續循環,知道成功或重試次數結束

    def select(self, sql=''):
        try:
            self._reConn()
            self._cursor()
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            self._free()
            return result
        except Exception as e:
            # print "Error %d: %s" % (e.args[0], e.args[1])
            return False

    def query(self, sql=''):
        try:
            self._reConn()
            self._cursor()
            result = self.cursor.execute(sql)
            self.conn.commit()
            self._free()
            return (True, result)
        except Exception as e:
            return False

    def close(self):
        self.conn.close()

if __name__ == "__main__":
    conn = mysql_connect(host="localhost",
                         user="root",
                         passwd="root",
                         db="test")

    data = conn.select("select id from shop_customer limit 10")
    print(data)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章