PooledDB created using the mysql Singleton

Take advantage of a single case is to reduce the link to the database, or after multiple links, mysql will collapse

Directly on the code:

class Mysql(object):
    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super(Mysql, cls).__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        self.mysql = PooledDB(creator=pymysql, mincached=10, maxcached=20,
                              host=settings.MYSQL_HOST,
                              port=settings.MYSQL_PORT,
                              user=settings.MYSQL_USER,
                              passwd=settings.MYSQL_PASSWORD,
                              db=settings.MYSQL_DB,
                              charset=settings.MYSQL_CHARSET)

    def getAll(self, sql):
        _conn = self.mysql.connection()
        _cursor = _conn.cursor(cursor=pymysql.cursors.DictCursor)
        _cursor.execute(sql)
        result = _cursor.fetchall()
        _cursor.close()
        _conn.close()
        return result

    def save_all(self, sql):
        _conn = self.mysql.connection()
        _cursor = _conn.cursor(cursor=pymysql.cursors.DictCursor)
        _cursor.execute(sql)
        _conn.commit()
        _cursor.close()
        _conn.close()


mysql = Mysql()
PooledDB parameters: 
1. mincached, the minimum number of idle connections, idle connection number is less than this number, the pool will create a new connection
2. maxcached, the maximum number of idle connections, if this number is greater than the number of idle connections, the pool will be closed idle connection
3. maxconnections, the maximum number of connections,
4. blocking, when the number of connections reaches the maximum number of connections, when the request for connection, if this value is True, the connection request program waits until the current number of connections less than the maximum number of connections, if the value is False, will complain,
5. maxshared when the number of connections reaches this number, will share new connection request has been allocated out of the connection
because here, in the project only uses mysql variable, so the above the role of several parameters is no reason Yongda

 

Before linking, so after each execution sql completed, should be close links

try:
    cursor.execute(sql)
finally:
    cursor.close()

 

Guess you like

Origin www.cnblogs.com/zjbacke/p/10930990.html
Recommended