Use the PooledDB connection pool of dbutils to operate the database

Use the PooledDB connection pool of dbutils to operate the database

# coding=utf-8
"""
Use the connections in the DBUtils database connection pool to operate the database
OperationalError: (2006, ‘MySQL server has gone away’)
"""
import json
import pymysql
import datetime
from DBUtils.PooledDB import PooledDB
import pymysql


class MysqlClient(object):
    __pool = None;
    def __init__(self, mincached=10, maxcached =20,maxshared=10, maxconnections=200, blocking=True,
                                             maxusage=50, setsession=None, reset=True,
                                             host='127.0.0.1', port=3306,db='test',
                                             user='root', passwd='123456',charset='utf8mb4'):
        if not self.__pool:
            self.__class__.__pool = PooledDB(pymysql,
                                             mincached, maxcached,
                                             maxshared, maxconnections, blocking,
                                             maxusage, setsession, reset,
                                             host=host, port=port,db=db,
                                             user=user, passwd=passwd,
                                             charset=charset,
                                             cursorclass=pymysql.cursors.DictCursor
                                             )
        self._conn = None
        self._cursor = None
        self.__get_conn()

    def __get_conn(self):
        self._conn = self.__pool.connection();
        self._cursor = self._conn.cursor();

    def __close(self):
        try:
            self.cursor.close()
            self.conn.close()
        except Exception as e:
            print e


    def __execute(self,sql,param=()):
        count = self._cursor.execute(sql,param)
        print count
        return count

    @staticmethod
    def  __dict_datetime_obj_to_str (result_dict):
         """ Convert the datatime object in the dictionary into a string, so that the json conversion does not go wrong """ 
        if result_dict:
            result_replace = { k:v.__str__() for k,v in result_dict.items()if isinstance(v,datetime.datetime)}
            result_dict.update(result_replace)
        return result_dict

    def select_one(self, sql, param= ()):
         """ Query a single result """ 
        count = self. __execute (sql,param)
        result = self._cursor.fetchone()
        """:type result:dict"""
        result = self.__dict_datetime_obj_to_str(result)
        return count,result

    def select_many(self,sql, param=()):
        """
        query multiple results
        :param sql: qsl statement
        :param param: sql parameter
        :return: number of results and query result set
        """
        count = self.__execute(sql, param)
        result = self._cursor.fetchall()
        """:type result:list"""
        [self.__dict_datetime_obj_to_str(row_dict) for row_dict in result]
        return count,result

    def execute(self,sql,param):
        count = self.__execute(sql,param)
        return count

    def begin(self):
         """ Start transaction """
        self._conn.autocommit(0)

    def end(self,option='commit'):
        """结束事务"""
        if option == 'commit':
            self._conn.autocommit()
        else:
            self._conn.rollback()


if __name__ == "__main__":
    mc = MysqlClient()
    sql1 = 'select * from shijiji  WHERE  id = 1'
    result1 = mc.select_one(sql1)
    print json.dumps(result1[1],ensure_ascii=False)

    sql2 = 'select * from shijiji  WHERE  id IN (%s,%s,%s)'
    param = (2,3,4)
    print json.dumps(mc.select_many(sql2,param)[1],ensure_ascii=False)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325069408&siteId=291194637