|--------| |--------------| | | <==borrow connection object== | Pool manager | | Client | | | | | ==return connection object==> | FIFO queue | |--------| |--------------|
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')
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。
依赖
pymysql:将依赖该工具包完成数据库的连接等操作;
pandas:测试时使用了 pandas。
以上就是Python MySQL数据库中pymysqlpool是如何使用的?的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于PythonMySQL数据库中pymysqlpool是如何使用的?的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did81892