標籤:python mysqldb dbutil sqlobject pooleddb
首先介紹下MySQLdb、DBUtil、sqlobject:
(1)MySQLdb 是用於Python串連Mysql資料庫的介面,它實現了 Python 資料庫 API 規範 V2.0,基於 MySQL C API 上建立的。除了MySQLdb外,python還可以通過oursql, PyMySQL, myconnpy等模組實現MySQL資料庫操作;
(2)DBUtil中提供了幾種串連池,用以提高資料庫的訪問效能,例如PooledDB,PesistentDB等
(3)sqlobject可以實現資料庫ORM映射的第三方模組,可以以對象、執行個體的方式輕鬆操作資料庫中記錄。
為測試這三者的效能,簡單做一個例子:50個並發訪問4000條記錄的單表,資料庫記錄如下:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/5B/59/wKioL1UHAynA120PAACIghwJV_M537.jpg" title="db.PNG" alt="wKioL1UHAynA120PAACIghwJV_M537.jpg" />
測試代碼如下:
1、MySQLdb的代碼如下,其中在connDB()中把串連池相關代碼暫時做了一個注釋,去掉這個注釋既可以使用串連池來建立資料庫連接:
(1)DBOperator.py
import MySQLdbfrom stockmining.stocks.setting import LoggerFactoryimport connectionpoolclass DBOperator(object): def __init__(self): self.logger = LoggerFactory.getLogger(‘DBOperator‘) self.conn = None def connDB(self): self.conn=MySQLdb.connect(host="127.0.0.1",user="root",passwd="root",db="pystock",port=3307,charset="utf8") #當需要使用串連池的時候開啟 #self.conn=connectionpool.pool.connection() return self.conn def closeDB(self): if(self.conn != None): self.conn.close() def execute(self, sql): try: if(self.conn != None): cursor = self.conn.cursor() else: raise MySQLdb.Error(‘No connection‘) n = cursor.execute(sql) return n except MySQLdb.Error,e: self.logger.error("Mysql Error %d: %s" % (e.args[0], e.args[1])) def findBySQL(self, sql): try: if(self.conn != None): cursor = self.conn.cursor() else: raise MySQLdb.Error(‘No connection‘) cursor.execute(sql) rows = cursor.fetchall() return rows except MySQLdb.Error,e: self.logger.error("Mysql Error %d: %s" % (e.args[0], e.args[1]))
(2)測試代碼testMysql.py,做了50個並發,對擷取到的資料庫記錄做了個簡單遍曆。
import threading import time import DBOperatordef run(): operator = DBOperator() operator.connDB() starttime = time.time() sql = "select * from stock_cash_tencent" peeps = operator.findBySQL(sql) for r in peeps: pass operator.closeDB() endtime = time.time() diff = (endtime - starttime)*1000 print diff def test(): for i in range(50): threading.Thread(target = run).start() time.sleep(1) if __name__ == ‘__main__‘: test()
2、串連池相關代碼:
(1)connectionpool.py
from DBUtils import PooledDBimport MySQLdbimport stringmaxconn = 30 #最大串連數mincached = 10 #最小空閑串連maxcached = 20 #最大空閑串連maxshared = 30 #最大共用串連connstring="root#root#127.0.0.1#3307#pystock#utf8" #資料庫地址dbtype = "mysql" def createConnectionPool(connstring, dbtype): db_conn = connstring.split("#"); if dbtype==‘mysql‘: try: pool = PooledDB.PooledDB(MySQLdb, user=db_conn[0],passwd=db_conn[1],host=db_conn[2],port=string.atoi(db_conn[3]),db=db_conn[4],charset=db_conn[5], mincached=mincached,maxcached=maxcached,maxshared=maxshared,maxconnections=maxconn) return pool except Exception, e: raise Exception,‘conn datasource Excepts,%s!!!(%s).‘%(db_conn[2],str(e)) return Nonepool = createConnectionPool(connstring, dbtype)
3、sqlobject相關代碼
(1)connection.py
from sqlobject.mysql import builderconn = builder()(user=‘root‘, password=‘root‘, host=‘127.0.0.1‘, db=‘pystock‘, port=3307, charset=‘utf8‘)
(2)StockCashTencent.py對應到資料庫中的表,50個並發並作了一個簡單的遍曆。(實際上,如果不做遍曆,只做count()計算,sqlobject效能是相當高的。)
import sqlobjectimport timefrom connection import connimport threadingclass StockCashTencent(sqlobject.SQLObject): _connection = conn code = sqlobject.StringCol() name = sqlobject.StringCol() date = sqlobject.StringCol() main_in_cash = sqlobject.FloatCol() main_out_cash = sqlobject.FloatCol() main_net_cash = sqlobject.FloatCol() main_net_rate= sqlobject.FloatCol() private_in_cash= sqlobject.FloatCol() private_out_cash= sqlobject.FloatCol() private_net_cash= sqlobject.FloatCol() private_net_rate= sqlobject.FloatCol() total_cash= sqlobject.FloatCol()def test(): starttime = time.time() query = StockCashTencent.select(True) for result in query: pass endtime = time.time() diff = (endtime - starttime)*1000 print diff if __name__ == ‘__main__‘: for i in range(50): threading.Thread(target = test).start() time.sleep(1)
測試結果如下:
MySQLdb平均(毫秒) |
99.63999271 |
DBUtil平均(毫秒) |
97.07998276 |
sqlobject平均(毫秒) |
343.2999897 |
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/5B/59/wKioL1UHAnXQKbJEAAD8JsxLQw8592.jpg" title="performace.PNG" alt="wKioL1UHAnXQKbJEAAD8JsxLQw8592.jpg" />
結論:其實就測試資料而言,MySQLdb單串連和DBUtil串連池的效能並沒有很大的區別(100個並發下也相差無幾),相反sqlobject雖然具有的編程上的便利性,但是卻帶來效能上的巨大不足,在實際中使用哪個模組就要斟酌而定了。
本文出自 “清茶一杯,風輕雲淡” 部落格,轉載請與作者聯絡!
python環境測試MySQLdb、DBUtil、sqlobject效能