python操作mysql數據庫的精美實用模塊(升級版)

寫在前面

之前,給大家分享過一個我自己寫的實用模塊:《python操作mysql數據庫的精美實用模塊》

這個模塊,我自己也一直在用的,沒出過什么BUG。但其實,這個代碼,也一直存在著一個不太優(yōu)雅的問題——

就是對數據庫進行了頻繁地創(chuàng)建連接和銷毀連接,這減慢了操作時間,也消耗了服務器內存。

最近,看到了 數據庫連接池技術,其實這個技術理解起來也很簡單,所以果斷對自己的代碼了進行升級。

當然,之前的《python操作mysql數據庫的精美實用模塊》也并非完全無用武之地了,就像我手上其中一個項目,因為之前整體構架的問題,偏偏就用不上數據庫連接池技術,上了反而會出問題。

凡事都有利有弊,大家都需要根據自己項目的情況,對應選擇運用合適自己項目的技術。

數據庫連接池技術

好了,正式介紹下這個技術:

連接池是一種常見的數據庫優(yōu)化技術,它可以減少數據庫連接的開銷,提高程序性能。

連接池的基本思想是在程序啟動時,創(chuàng)建一定數量的數據庫連接,并保存在一個容器中。

當程序需要訪問數據庫時,從容器中獲取一個空閑的連接,使用完畢后,將連接歸還到容器中,而不是關閉連接。

DBUtils 庫

DBUtils 是一個常用的 Python 的第三方數據庫連接池庫,支持多種數據庫,包括 MySQL、PostgreSQL、SQLite 等。

網上相關資料,也是比較豐富的,如需詳細了解,大家自行搜索資料吧。

這里按照我的風格慣例,給大家直接上我自己寫好的實用模塊,方便拿走即用。

其中,我的初代版《python操作mysql數據庫的精美實用模塊》也已經改為類實現了,這次一起奉上。

python操作mysql數據庫的精美實用模塊—— DBUtils連接池版

import pymysql
from dbutils.pooled_db import PooledDB
#############################################################################################
# 連接mysql數據庫-----使用數據庫連接池技術----dbutils庫
#############################################################################################
db_pool = PooledDB(
    creator=pymysql,  # 使用鏈接數據庫的模塊
    maxconnections=800,  # 連接池允許的最大連接數,0和None表示不限制連接數
    mincached=8,  # 初始化時,鏈接池中至少創(chuàng)建的空閑的鏈接,0表示不創(chuàng)建
    blocking=True,  # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯
    maxusage=None,  # 一個鏈接最多被重復使用的次數,None表示無限制
    setsession=[],  # 開始會話前執(zhí)行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    ping=0,   # ping MySQL服務端,檢查是否服務可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always

    host='127.0.0.1',
    port=3306,
    user='root'
    password='root',
    database='mydbdemo',
    charset='utf8'
)



class DBManager():
    # 創(chuàng)建數據庫連接
    def __init__(self):
        self.db = db_pool.connection()

    # 關閉數據庫連接
    def closeDB(self):
        self.db.close()


    #連接數據庫,執(zhí)行插入SQl
    def executeQueryID(self,sqlstring):
        try:
            cursor = self.db.cursor()
            cursor.execute(sqlstring)
            self.db.commit()
            the_id = int(cursor.lastrowid)
            #the_id = int(db.insert_id())
            return the_id
        except Exception:
            return False
        finally:
            self.db.close()  # 關閉數據庫連接




    # 連接數據庫,執(zhí)行SQl,無返回
    def executeQueryNO(self, sqlstring):
        try:
            cursor = self.db.cursor()
            cursor.execute(sqlstring)
            self.db.commit()
            return True
        except Exception:
            self.db.rollback()
            return False
        finally:
            self.db.close()  # 關閉數據庫連接


    #連接數據庫,執(zhí)行SQL,返回單條數據
    def executeQueryone(self, sqlstring):
        try:
            cursor = self.db.cursor()
            cursor.execute(sqlstring)
            dataone = cursor.fetchone()
            return dataone
        except Exception:
            return False
        finally:
            self.db.close()  # 關閉數據庫連接

    #連接數據庫,執(zhí)行SQL,返回多條數據
    def executeQueryall(self, sqlstring):
        try:
            cursor = self.db.cursor()
            cursor.execute(sqlstring)
            dataall = cursor.fetchall()
            return dataall
        except Exception:
            return False
        finally:
            self.db.close()  # 關閉數據庫連接





python操作mysql數據庫的精美實用模塊—— 原版改用類實現

##############################################################################################
# 連接mysql數據庫
#############################################################################################
class DBManager_Old():
    # 創(chuàng)建數據庫連接
    def __init__(self):
        db_config = ConfigManager.get_db_config()
        self.db = pymysql.Connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        passwd='root',
        db='mydbdemo',
        charset='utf8')

    # 關閉數據庫連接
    def closeDB(self):
        self.db.close()

    #連接數據庫,執(zhí)行插入SQl
    def executeQueryID(self,sqlstring):
        try:
            cursor = self.db.cursor()
            cursor.execute(sqlstring)
            self.db.commit()
            the_id = int(cursor.lastrowid)
            #the_id = int(db.insert_id())
            return the_id
        except Exception:
            return False
        finally:
            self.db.close()  # 關閉數據庫連接




    # 連接數據庫,執(zhí)行SQl,無返回
    def executeQueryNO(self, sqlstring):
        try:
            cursor = self.db.cursor()
            cursor.execute(sqlstring)
            self.db.commit()
            return True
        except Exception:
            self.db.rollback()
            return False
        finally:
            self.db.close()  # 關閉數據庫連接


    #連接數據庫,執(zhí)行SQL,返回單條數據
    def executeQueryone(self, sqlstring):
        try:
            cursor = self.db.cursor()
            cursor.execute(sqlstring)
            dataone = cursor.fetchone()
            return dataone
        except Exception:
            return False
        finally:
            self.db.close()  # 關閉數據庫連接

    #連接數據庫,執(zhí)行SQL,返回多條數據
    def executeQueryall(self, sqlstring):
        try:
            cursor = self.db.cursor()
            cursor.execute(sqlstring)
            dataall = cursor.fetchall()
            return dataall
        except Exception:
            return False
        finally:
            self.db.close()  # 關閉數據庫連接

寫在最后

所以,你看,大家平時學習或開發(fā)時,發(fā)現更好更合適的技術或方法,就要積極去升級自己項目的代碼,這就是所謂的重構。

《程序員修煉之道》有言:盡早重構,經常重構。

重構的思想精髓,就是不斷地去升級項目的代碼,同時,這個過程也在不斷地修煉自己的技術。

其實,代碼需要重構,整個項目也需要重構,我們的能力也需要重構,我們的人生也需要重構。

重構,不是推倒重來,是在現有的基礎上,一步一步,不斷去升級,去變得更好。

這其實就是修煉啊,人生本就是一場修煉。

這就是我理解的重構。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容