💡 About
This is a dynamic connection pool for mysqlclient connector and size of it grows as it requires. Extra connections will be terminated automatically if they're no longer needed.
The connection pool won't check the connectivity state of the connections before passing them to the user because in any time is still possible for the connection to drop in middle of the query. The user itself should watch for the disconnections.
The connection pool is thread-safe and can be shared on multithreaded context as long as the individual connection object not shared between the threads. However individual pool instances are required for different processes.
🔌 Installation
pip install mysqlclient-pool
📋 How to Use
Instantiating the connection pool. The pool also can be instantiated as a context manager using with
statement.
from mysqlclient_pool import ConnectionPool
from MySQLdb._exceptions import OperationalError, ProgrammingError
try:
pool = ConnectionPool(
{
"unix_socket": "/var/run/mysqld/mysqld.sock",
"host": "localhost",
"port": 3306,
"user": "root",
"password": "...",
"database": "mysql"
},
size=20,
timeout=10
)
except TimeoutError:
pass
Acquiring a cursor
object from the pool. fetch()
method commits or rollbacks the changes by default.
try:
with pool.fetch() as cursor:
cursor.execute("SELECT DATABASE()")
print(cursor.fetchone())
except (OperationalError, ProgrammingError):
pass
except pool.OverflowError:
pass
except pool.DrainedError:
pass
connection
object also can be accessed if needed. But any changes to connection should be reverted when returning the connection back to the pool.
with pool.fetch() as cursor:
try:
cursor.connection.autocommit(True)
cursor.execute("INSERT INTO ...")
cursor.execute("UPDATE ...")
cursor.execute("DELETE FROM ...")
finally:
cursor.connection.autocommit(False)
Closing the pool when it's not needed anymore.
pool.close()
🔧 API