安裝DBUtils庫:
python3 -m pip install DBUtils去安裝DBUtils庫
通過連接配接池的方式去建立資料庫對象:
這裡參考我的上一篇部落格:http://www.cnblogs.com/letmeiscool/p/8434381.html和DBUtils使用者指南:http://blog.csdn.net/gashero/article/details/1577187去寫。單獨寫了個建立連接配接池的方法,在建立資料庫對象的時候被執行。之後每次去執行sql的時候,不需要去建立連接配接池,隻需要每次執行sql前去執行連接配接方法_Getconnect,sql執行完畢,去關閉連接配接,連接配接被資料庫連接配接池給回收。
#-*-coding:utf-8-*-s
#mysql和sqlserver的庫
import pymysql,pymssql
from DBUtils.PooledDB import PooledDB
class Database:
def __init__(self,*db):
if len(db)==5:
#mysql資料庫
self.host=db[0]
self.port=db[1]
self.user=db[2]
self.pwd=db[3]
self.db=db[4]
else:
#sqlserver資料庫
self.host=db[0]
self.port=None
self.user=db[1]
self.pwd=db[2]
self.db=db[3]
self._CreatePool()
def _CreatePool(self):
if not self.db:
raise NameError+"沒有設定資料庫資訊"
if (self.port==None):
self.Pool=PooledDB(creator=pymssql,mincached=2, maxcached=5,maxshared=3, maxconnections=6, blocking=True,host=self.host,user=self.user, \
password=self.pwd,database=self.db,charset="utf8")
else:
self.Pool=PooledDB(creator=pymysql,mincached=2, maxcached=5,maxshared=3, maxconnections=6, blocking=True,host=self.host,port=self.port, \
user=self.user,password=self.pwd,database =self.db,charset="utf8")
def _Getconnect(self):
self.conn=self.Pool.connection()
cur=self.conn.cursor()
if not cur:
raise "資料庫連接配接不上"
else:
return cur
#查詢sql
def ExecQuery(self,sql):
cur=self._Getconnect()
cur.execute(sql)
relist=cur.fetchall()
cur.close()
self.conn.close()
return relist
#非查詢的sql
def ExecNoQuery(self,sql):
cur=self._Getconnect()
cur.execute(sql)
self.conn.commit()
cur.close()
self.conn.close()
PooledDB的參數:
dbapi: 需要使用的DB-API 2子產品
mincached : 啟動時開啟的空連接配接數量(預設值 0 意味着開始時不建立連接配接)
maxcached: 連接配接池使用的最多連接配接數量(預設值 0 代表不限制連接配接池大小)
maxshared: 最大允許的共享連接配接數量(預設值 0 代表所有連接配接都是專用的)如果達到了最大數量,被請求為共享的連接配接将會被共享使用。
maxconnections: 最大允許連接配接數量(預設值 0 代表不限制)
blocking: 設定在達到最大數量時的行為(預設值 0 或 False 代表傳回一個錯誤;其他代表阻塞直到連接配接數減少)
maxusage: 單個連接配接的最大允許複用次數(預設值 0 或 False 代表不限制的複用)。當達到最大數值時,連接配接會自動重新連接配接(關閉和重新打開)
setsession: 一個可選的SQL指令清單用于準備每個會話,如 ["set datestyle to german", ...]
其他,你可以設定用于傳遞到真正的DB-API 2的參數,例如主機名、資料庫、使用者名、密碼等。