Python實(shí)現(xiàn)Mysql數(shù)據(jù)庫(kù)連接池實(shí)例詳解
python連接Mysql數(shù)據(jù)庫(kù):
Python編程中可以使用MySQLdb進(jìn)行數(shù)據(jù)庫(kù)的連接及諸如查詢(xún)/插入/更新等操作,但是每次連接MySQL數(shù)據(jù)庫(kù)請(qǐng)求時(shí),都是獨(dú)立的去請(qǐng)求訪問(wèn),相當(dāng)浪費(fèi)資源,而且訪問(wèn)數(shù)量達(dá)到一定數(shù)量時(shí),對(duì)mysql的性能會(huì)產(chǎn)生較大的影響。因此,實(shí)際使用中,通常會(huì)使用數(shù)據(jù)庫(kù)的連接池技術(shù),來(lái)訪問(wèn)數(shù)據(jù)庫(kù)達(dá)到資源復(fù)用的目的。
數(shù)據(jù)庫(kù)連接池

python的數(shù)據(jù)庫(kù)連接池包 DBUtils:
DBUtils是一套Python數(shù)據(jù)庫(kù)連接池包,并允許對(duì)非線(xiàn)程安全的數(shù)據(jù)庫(kù)接口進(jìn)行線(xiàn)程安全包裝。DBUtils來(lái)自Webware for Python。
DBUtils提供兩種外部接口:
* PersistentDB :提供線(xiàn)程專(zhuān)用的數(shù)據(jù)庫(kù)連接,并自動(dòng)管理連接。
* PooledDB :提供線(xiàn)程間可共享的數(shù)據(jù)庫(kù)連接,并自動(dòng)管理連接。
下載地址:DBUtils 下載解壓后,使用python setup.py install 命令進(jìn)行安裝
下面利用MySQLdb和DBUtils建立自己的mysql數(shù)據(jù)庫(kù)連接池工具包
在工程目錄下新建package命名為:dbConnecttion,并新建module命名為MySqlConn,下面是MySqlConn.py,該模塊創(chuàng)建Mysql的連接池對(duì)象,并創(chuàng)建了如查詢(xún)/插入等通用的操作方法。該部分代碼實(shí)現(xiàn)如下:
# -*- coding: UTF-8 -*-
"""
Created on 2016年5月7日
@author: baocheng
1、執(zhí)行帶參數(shù)的SQL時(shí),請(qǐng)先用sql語(yǔ)句指定需要輸入的條件列表,然后再用tuple/list進(jìn)行條件批配
2、在格式SQL中不需要使用引號(hào)指定數(shù)據(jù)類(lèi)型,系統(tǒng)會(huì)根據(jù)輸入?yún)?shù)自動(dòng)識(shí)別
3、在輸入的值中不需要使用轉(zhuǎn)意函數(shù),系統(tǒng)會(huì)自動(dòng)處理
"""
import MySQLdb
from MySQLdb.cursors import DictCursor
from DBUtils.PooledDB import PooledDB
#from PooledDB import PooledDB
import Config
"""
Config是一些數(shù)據(jù)庫(kù)的配置文件
"""
class Mysql(object):
"""
MYSQL數(shù)據(jù)庫(kù)對(duì)象,負(fù)責(zé)產(chǎn)生數(shù)據(jù)庫(kù)連接 , 此類(lèi)中的連接采用連接池實(shí)現(xiàn)獲取連接對(duì)象:conn = Mysql.getConn()
釋放連接對(duì)象;conn.close()或del conn
"""
#連接池對(duì)象
__pool = None
def __init__(self):
#數(shù)據(jù)庫(kù)構(gòu)造函數(shù),從連接池中取出連接,并生成操作游標(biāo)
self._conn = Mysql.__getConn()
self._cursor = self._conn.cursor()
@staticmethod
def __getConn():
"""
@summary: 靜態(tài)方法,從連接池中取出連接
@return MySQLdb.connection
"""
if Mysql.__pool is None:
__pool = PooledDB(creator=MySQLdb, mincached=1 , maxcached=20 ,
host=Config.DBHOST , port=Config.DBPORT , user=Config.DBUSER , passwd=Config.DBPWD ,
db=Config.DBNAME,use_unicode=False,charset=Config.DBCHAR,cursorclass=DictCursor)
return __pool.connection()
def getAll(self,sql,param=None):
"""
@summary: 執(zhí)行查詢(xún),并取出所有結(jié)果集
@param sql:查詢(xún)SQL,如果有查詢(xún)條件,請(qǐng)只指定條件列表,并將條件值使用參數(shù)[param]傳遞進(jìn)來(lái)
@param param: 可選參數(shù),條件列表值(元組/列表)
@return: result list(字典對(duì)象)/boolean 查詢(xún)到的結(jié)果集
"""
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql,param)
if count>0:
result = self._cursor.fetchall()
else:
result = False
return result
def getOne(self,sql,param=None):
"""
@summary: 執(zhí)行查詢(xún),并取出第一條
@param sql:查詢(xún)SQL,如果有查詢(xún)條件,請(qǐng)只指定條件列表,并將條件值使用參數(shù)[param]傳遞進(jìn)來(lái)
@param param: 可選參數(shù),條件列表值(元組/列表)
@return: result list/boolean 查詢(xún)到的結(jié)果集
"""
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql,param)
if count>0:
result = self._cursor.fetchone()
else:
result = False
return result
def getMany(self,sql,num,param=None):
"""
@summary: 執(zhí)行查詢(xún),并取出num條結(jié)果
@param sql:查詢(xún)SQL,如果有查詢(xún)條件,請(qǐng)只指定條件列表,并將條件值使用參數(shù)[param]傳遞進(jìn)來(lái)
@param num:取得的結(jié)果條數(shù)
@param param: 可選參數(shù),條件列表值(元組/列表)
@return: result list/boolean 查詢(xún)到的結(jié)果集
"""
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql,param)
if count>0:
result = self._cursor.fetchmany(num)
else:
result = False
return result
def insertOne(self,sql,value):
"""
@summary: 向數(shù)據(jù)表插入一條記錄
@param sql:要插入的SQL格式
@param value:要插入的記錄數(shù)據(jù)tuple/list
@return: insertId 受影響的行數(shù)
"""
self._cursor.execute(sql,value)
return self.__getInsertId()
def insertMany(self,sql,values):
"""
@summary: 向數(shù)據(jù)表插入多條記錄
@param sql:要插入的SQL格式
@param values:要插入的記錄數(shù)據(jù)tuple(tuple)/list[list]
@return: count 受影響的行數(shù)
"""
count = self._cursor.executemany(sql,values)
return count
def __getInsertId(self):
"""
獲取當(dāng)前連接最后一次插入操作生成的id,如果沒(méi)有則為0
"""
self._cursor.execute("SELECT @@IDENTITY AS id")
result = self._cursor.fetchall()
return result[0]['id']
def __query(self,sql,param=None):
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql,param)
return count
def update(self,sql,param=None):
"""
@summary: 更新數(shù)據(jù)表記錄
@param sql: SQL格式及條件,使用(%s,%s)
@param param: 要更新的 值 tuple/list
@return: count 受影響的行數(shù)
"""
return self.__query(sql,param)
def delete(self,sql,param=None):
"""
@summary: 刪除數(shù)據(jù)表記錄
@param sql: SQL格式及條件,使用(%s,%s)
@param param: 要?jiǎng)h除的條件 值 tuple/list
@return: count 受影響的行數(shù)
"""
return self.__query(sql,param)
def begin(self):
"""
@summary: 開(kāi)啟事務(wù)
"""
self._conn.autocommit(0)
def end(self,option='commit'):
"""
@summary: 結(jié)束事務(wù)
"""
if option=='commit':
self._conn.commit()
else:
self._conn.rollback()
def dispose(self,isEnd=1):
"""
@summary: 釋放連接池資源
"""
if isEnd==1:
self.end('commit')
else:
self.end('rollback');
self._cursor.close()
self._conn.close()
配置文件模塊Cnofig,包括數(shù)據(jù)庫(kù)的連接信息/用戶(hù)名密碼等:
#coding:utf-8 ''''' Created on 2016年5月7日 @author: baocheng ''' DBHOST = "localhost" DBPORT = 33606 DBUSER = "zbc" DBPWD = "123456" DBNAME = "test" DBCHAR = "utf8"
創(chuàng)建test模塊,測(cè)試一下使用連接池進(jìn)行mysql訪問(wèn):
#coding:utf-8 ''''' @author: baocheng ''' from MySqlConn import Mysql from _sqlite3 import Row #申請(qǐng)資源 mysql = Mysql() sqlAll = "SELECT tb.uid as uid, group_concat(tb.goodsname) as goodsname FROM ( SELECT goods.uid AS uid, IF ( ISNULL(goodsrelation.goodsname), goods.goodsID, goodsrelation.goodsname ) AS goodsname FROM goods LEFT JOIN goodsrelation ON goods.goodsID = goodsrelation.goodsId ) tb GROUP BY tb.uid" result = mysql.getAll(sqlAll) if result : print "get all" for row in result : print "%s\t%s"%(row["uid"],row["goodsname"]) sqlAll = "SELECT tb.uid as uid, group_concat(tb.goodsname) as goodsname FROM ( SELECT goods.uid AS uid, IF ( ISNULL(goodsrelation.goodsname), goods.goodsID, goodsrelation.goodsname ) AS goodsname FROM goods LEFT JOIN goodsrelation ON goods.goodsID = goodsrelation.goodsId ) tb GROUP BY tb.uid" result = mysql.getMany(sqlAll,2) if result : print "get many" for row in result : print "%s\t%s"%(row["uid"],row["goodsname"]) result = mysql.getOne(sqlAll) print "get one" print "%s\t%s"%(result["uid"],result["goodsname"]) #釋放資源 mysql.dispose()
當(dāng)然,還有很多其他參數(shù)可以配置:
- dbapi :數(shù)據(jù)庫(kù)接口
- mincached :?jiǎn)?dòng)時(shí)開(kāi)啟的空連接數(shù)量
- maxcached :連接池最大可用連接數(shù)量
- maxshared :連接池最大可共享連接數(shù)量
- maxconnections :最大允許連接數(shù)量
- blocking :達(dá)到最大數(shù)量時(shí)是否阻塞
- maxusage :?jiǎn)蝹€(gè)連接最大復(fù)用次數(shù)
根據(jù)自己的需要合理配置上述的資源參數(shù),以滿(mǎn)足自己的實(shí)際需要。
至此,python中的mysql連接池實(shí)現(xiàn)完了,下次就直接拿來(lái)用就好了。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
- python連接池實(shí)現(xiàn)示例程序
- Python MySQL數(shù)據(jù)庫(kù)連接池組件pymysqlpool詳解
- 構(gòu)建高效的python requests長(zhǎng)連接池詳解
- Python3 多線(xiàn)程(連接池)操作MySQL插入數(shù)據(jù)
- 分析解決Python中sqlalchemy數(shù)據(jù)庫(kù)連接池QueuePool異常
- Python 中創(chuàng)建 PostgreSQL 數(shù)據(jù)庫(kù)連接池
- python自制簡(jiǎn)易mysql連接池的實(shí)現(xiàn)示例
- Python封裝數(shù)據(jù)庫(kù)連接池詳解
相關(guān)文章
Python sklearn對(duì)文本數(shù)據(jù)進(jìn)行特征化提取
這篇文章主要介紹了Python sklearn對(duì)文本數(shù)據(jù)進(jìn)行特征化提取,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-04-04
windows下搭建python scrapy爬蟲(chóng)框架步驟
在本文內(nèi)容里小編給大家分享的是關(guān)于windows下搭建python scrapy爬蟲(chóng)框架的教學(xué)內(nèi)容,需要的朋友們學(xué)習(xí)下。2018-12-12
Python+Selenium實(shí)現(xiàn)瀏覽器的控制操作
這篇文章主要為大家詳細(xì)介紹了Python+Selenium如何實(shí)現(xiàn)常見(jiàn)的瀏覽器控制操作,例如:瀏覽器參數(shù)設(shè)置、控制瀏覽器前進(jìn)/后退等,感興趣的可以了解一下2022-09-09
Python中初始化一個(gè)二維數(shù)組及注意事項(xiàng)說(shuō)明
這篇文章主要介紹了Python中初始化一個(gè)二維數(shù)組及注意事項(xiàng)說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Keras實(shí)現(xiàn)支持masking的Flatten層代碼
這篇文章主要介紹了Keras實(shí)現(xiàn)支持masking的Flatten層代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python for循環(huán)搭配else常見(jiàn)問(wèn)題解決
這篇文章主要介紹了Python for循環(huán)搭配else常見(jiàn)問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02

