时间:2020-10-25 14:42:04 | 栏目:Python代码 | 点击:次
引言
pymysqlpool (本地下载)是数据库工具包中新成员,目的是能提供一个实用的数据库连接池中间件,从而避免在应用中频繁地创建和释放数据库连接资源。
功能
pymysql.Connection
);基本工作流程
注意,当多线程同时请求时,若池中没有可用的连接对象,则需要排队等待
|--------| |--------------| | | <==borrow connection object== | Pool manager | | Client | | | | | ==return connection object==> | FIFO queue | |--------| |--------------|
参数配置
pymysql.Connection
使用示例
1、使用 cursor 上下文管理器(快捷方式,但每次获取都会申请连接对象,多次调用效率不高):
from pymysqlpool import ConnectionPool config = { 'pool_name': 'test', 'host': 'localhost', 'port': 3306, 'user': 'root', 'password': 'root', 'database': 'test' } def connection_pool(): # Return a connection pool instance pool = ConnectionPool(**config) pool.connect() return pool # 直接访问并获取一个 cursor 对象,自动 commit 模式会在这种方式下启用 with connection_pool().cursor() as cursor: print('Truncate table user') cursor.execute('TRUNCATE user') print('Insert one record') result = cursor.execute('INSERT INTO user (name, age) VALUES (%s, %s)', ('Jerry', 20)) print(result, cursor.lastrowid) print('Insert multiple records') users = [(name, age) for name in ['Jacky', 'Mary', 'Micheal'] for age in range(10, 15)] result = cursor.executemany('INSERT INTO user (name, age) VALUES (%s, %s)', users) print(result) print('View items in table user') cursor.execute('SELECT * FROM user') for user in cursor: print(user) print('Update the name of one user in the table') cursor.execute('UPDATE user SET name="Chris", age=29 WHERE id = 16') cursor.execute('SELECT * FROM user ORDER BY id DESC LIMIT 1') print(cursor.fetchone()) print('Delete the last record') cursor.execute('DELETE FROM user WHERE id = 16')
2、使用 connection 上下文管理器:
import pandas as pd from pymysqlpool import ConnectionPool config = { 'pool_name': 'test', 'host': 'localhost', 'port': 3306, 'user': 'root', 'password': 'root', 'database': 'test' } def connection_pool(): # Return a connection pool instance pool = ConnectionPool(**config) pool.connect() return pool with connection_pool().connection() as conn: pd.read_sql('SELECT * FROM user', conn) # 或者 connection = connection_pool().borrow_connection() pd.read_sql('SELECT * FROM user', conn) connection_pool().return_connection(connection)
更多测试请移步 test_example.py。
依赖
安装
轻移步 pymysqlpool: https://github.com/ChrisLeeGit/pymysqlpool 下载源码(也可以通过本地下载),然后使用 pip 安装即可:pip3 setup.py install
,注意需要使用 Python3 环境。
总结