引言
pymysqlpool 是数据库工具包中新成员,目的是能提供一个实用的数据库连接池中间件,从而避免在应用中频繁地创建和释放数据库连接资源。
功能
基本工作流程
注意,当多线程同时请求时,若池中没有可用的连接对象,则需要排队等待
- |--------| |--------------|
- | | <==borrow connection object== | Pool manager |
- | Client | | |
- | | ==return connection object==> | FIFO queue |
- |--------| |--------------|
数配置
使用示例
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)
3.更多测试请移步 test_example.py 。
依赖
1.pymysql :将依赖该工具包完成数据库的连接等操作;
2.pandas :测试时使用了 pandas。
安装
1.移步 pymysqlpool: https://github.com/ChrisLeeGit/pymysqlpool 下载源码,然后使用 pip 安装即可: pip3 setup.py install ,注意需要使用 Python3 环境。
2.欢迎反馈,共同学习进步
当前文章:PythonMySQL数据库连接池组件
转载注明:http://www.shufengxianlan.com/qtweb/news23/460473.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联