1. 程式人生 > >python單例與資料庫連線池

python單例與資料庫連線池

 單例:專業用來處理連線多的問題(比如連線redis,zookeeper等),全域性只有一個物件

 

單例程式碼
def
singleton(cls): instances = {} def _singleton(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return _singleton

例項程式碼

from singleton import singleton

#@singleton
class  MysqlOpers:
    
    def __init__(self):
        print('建立mysql連線')
        #虛擬碼  self.db = MySQLdb.connect()
        
    def select(self):
        pass
    
m = MysqlOpers()
n = MysqlOpers()
c = MysqlOpers()

print(id(m))
print(id(n))
print(id(c))

 

 

加上單例裝飾器後

 

mysql 連線池

#coding=utf-8

import traceback

import MySQLdb
from DBUtils.PooledDB import PooledDB


db_pool_ins = None

#需要替換使用者名稱,密碼等
class DBPool():
    def __init__(self):
        self.pool = PooledDB(creator=MySQLdb, mincached=1, maxcached=10, maxconnections=100, blocking=True, 
                             host
= "127.0.0.1", port=3306, user='', passwd='', db='test', charset='utf8',) def get_connection(self): return self.pool.connection() class DBAction(): #連線池物件 def __init__(self): #建立和資料庫系統的連線 global db_pool_ins if db_pool_ins == None: db_pool_ins = DBPool() self.conn = db_pool_ins.get_connection() #獲取操作遊標 self.cursor = self.conn.cursor() def close_database(self): self.cursor.close() self.conn.close() def data_operate(self, sql, params=()): ''' 資料的插入,更新,刪除 :param database: :param sql: :return: 成功:0,失敗:1 ''' try: self.cursor.execute(sql, params) self.conn.commit() return 0 except: print("sql is %s, params is %s error. %s" % (sql, params, traceback.format_exc())) self.conn.rollback() raise Exception def data_operate_many(self, sql, params=()): ''' 資料的插入,更新,刪除 :param sql: :param params: :return: 成功:0,失敗:1 ''' #執行sql語句 self.cursor.executemany(sql, params) #提交到資料庫執行 self.conn.commit() def data_operate_count(self, sql, params=()): ''' 資料的插入,更新,刪除 :return: 受影響的條數 ''' #執行sql語句 count = self.cursor.execute(sql, params) #提交到資料庫執行 self.conn.commit() return count def data_inquiry(self, sql, size=10, params=()): ''' :param database: :param sql: :return: ((),(),...,()) ''' self.cursor.execute(sql, params) result = self.cursor.fetchmany(size) return result def data_inquiry_all(self, sql, params=()): ''' :param database: :param sql: :return: ((),(),...,()) ''' self.cursor.execute(sql, params) result = self.cursor.fetchall() return result def commit(self): self.conn.commit()

 

使用


from mysql import DBAction

dba = DBAction()
ret = dba.data_inquiry_all("SELECT * FROM friend")
print(ret)