1. 程式人生 > >python 學習筆記(十): 資料庫連線池

python 學習筆記(十): 資料庫連線池

#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import Queue
import pymysql
import logging


LOG = logging.getLogger(__name__)

class ConnectionPool(object):
    # 例項化類的時候建立連線池
    def __init__(self,**kwargs):
        self.rowSize = kwargs.get('size',10)
        self.kwargs = kwargs
        self.conn_queue = Queue.Queue.maxsize(self.rowSize) # 建立一個固定長度的queue佇列
for i in range(self.rowSize): # todo 建立連線 conn = self._create_new_conn(self.kwargs) self._put_conn(conn) # 連線資料庫 這裡不做上下文管理,因為需要在保持資料庫連線 def _create_new_conn(self): return pymysql.connect( host=self.kwargs.get('host','127.0.0.1'
),user=self.kwargs.get('user'), passwd=self.kwargs.get('password'),port=self.kwargs.get('port',3306), db=self.kwargs.get('db') ) # 把資源放入佇列 def _put_conn(self,conn): if conn: self.conn_queue.put(conn) # 獲取資源 def _get_conn(self): conn = self.conn_queue.get(); if
conn is None: self._create_new_conn() return conn def exec_sql(self,sql): conn = self._get_conn(); try: with conn as cur: cur.execute(sql) return cur.fetchall() except pymysql.ProgrammingError as e: LOG.error('execute sql ({0}) error {1}'.format(sql,e)) except pymysql.OperationalError as e: self._create_new_conn() raise e finally: self._put_conn(conn) def __del__(self): try: while True: conn = self.conn_queue.get_nowait() if conn: conn.close() except Queue.Empty: pass