pymysql 线程安全pymysqlpool
# -*-coding: utf-8-*-
# Author : Christopher Lee
# License: Apache License
# File : test_example.py
# Date : 2017-06-18 01-23
# Version: 0.0.1
# Description: simple test. import logging
import string
import threading import pandas as pd
import random from pymysqlpool import ConnectionPool config = {
'pool_name': 'test',
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': 'chris',
'database': 'test',
'pool_resize_boundary': 50,
'enable_auto_resize': True,
# 'max_pool_size': 10
} logging.basicConfig(format='[%(asctime)s][%(name)s][%(module)s.%(lineno)d][%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.DEBUG) def connection_pool():
# Return a connection pool instance
pool = ConnectionPool(**config)
# pool.connect()
return pool def test_pool_cursor(cursor_obj=None):
cursor_obj = cursor_obj or connection_pool().cursor()
with cursor_obj 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') def test_pool_connection():
with connection_pool().connection(autocommit=True) as conn:
test_pool_cursor(conn.cursor()) def test_with_pandas():
with connection_pool().connection() as conn:
df = pd.read_sql('SELECT * FROM user', conn)
print(df) def delete_users():
with connection_pool().cursor() as cursor:
cursor.execute('TRUNCATE user') def add_users(users, conn):
def execute(c):
c.cursor().executemany('INSERT INTO user (name, age) VALUES (%s, %s)', users)
c.commit() if conn:
execute(conn)
return
with connection_pool().connection() as conn:
execute(conn) def add_user(user, conn=None):
def execute(c):
c.cursor().execute('INSERT INTO user (name, age) VALUES (%s, %s)', user)
c.commit() if conn:
execute(conn)
return
with connection_pool().connection() as conn:
execute(conn) def list_users():
with connection_pool().cursor() as cursor:
cursor.execute('SELECT * FROM user ORDER BY id DESC LIMIT 5')
print('...')
for x in sorted(cursor, key=lambda d: d['id']):
print(x) def random_user():
name = "".join(random.sample(string.ascii_lowercase, random.randint(4, 10))).capitalize()
age = random.randint(10, 40)
return name, age def worker(id_, batch_size=1, explicit_conn=True):
print('[{}] Worker started...'.format(id_)) def do(conn=None):
for _ in range(batch_size):
add_user(random_user(), conn) if not explicit_conn:
do()
return with connection_pool().connection() as c:
do(c) print('[{}] Worker finished...'.format(id_)) def bulk_worker(id_, batch_size=1, explicit_conn=True):
print('[{}] Bulk worker started...'.format(id_)) def do(conn=None):
add_users([random_user() for _ in range(batch_size)], conn)
time.sleep(3) if not explicit_conn:
do()
return with connection_pool().connection() as c:
do(c) print('[{}] Worker finished...'.format(id_)) def test_with_single_thread(batch_number, batch_size, explicit_conn=False, bulk_insert=False):
delete_users()
wk = worker if not bulk_insert else bulk_worker
for i in range(batch_number):
wk(i, batch_size, explicit_conn)
list_users() def test_with_multi_threads(batch_number=1, batch_size=1000, explicit_conn=False, bulk_insert=False):
delete_users() wk = worker if not bulk_insert else bulk_worker threads = []
for i in range(batch_number):
t = threading.Thread(target=wk, args=(i, batch_size, explicit_conn))
threads.append(t)
t.start() [t.join() for t in threads]
list_users() if __name__ == '__main__':
import time start = time.perf_counter()
test_pool_cursor()
test_pool_connection() test_with_pandas()
test_with_multi_threads(20, 10, True, bulk_insert=True)
test_with_single_thread(1, 10, True, bulk_insert=True)
elapsed = time.perf_counter() - start
print('Elapsed time is: "{}"'.format(elapsed))
pymysql 线程安全pymysqlpool的更多相关文章
- 杂项之pymysql连接池
杂项之pymysql连接池 本节内容 本文的诞生 连接池及单例模式 多线程提升 协程提升 后记 1.本文的诞生 由于前几天接触了pymysql,在测试数据过程中,使用普通的pymysql插入100W条 ...
- 第一篇:杂项之pymysql连接池
杂项之pymysql连接池 杂项之pymysql连接池 本节内容 本文的诞生 连接池及单例模式 多线程提升 协程提升 后记 1.本文的诞生 由于前几天接触了pymysql,在测试数据过程中,使用普 ...
- Day12 线程池、RabbitMQ和SQLAlchemy
1.with实现上下文管理 #!/usr/bin/env python# -*- coding: utf-8 -*-# Author: wanghuafeng #with实现上下文管理import c ...
- python运维开发(十二)----rabbitMQ、pymysql、SQLAlchemy
内容目录: rabbitMQ python操作mysql,pymysql模块 Python ORM框架,SQLAchemy模块 Paramiko 其他with上下文切换 rabbitMQ Rabbit ...
- 3、flask之基于DBUtils实现数据库连接池、本地线程、上下文
本篇导航: 数据库连接池 本地线程 上下文管理 面向对象部分知识点解析 1.子类继承父类__init__的三种方式 class Dog(Animal): #子类 派生类 def __init__(se ...
- python全栈开发day113-DBUtils(pymysql数据连接池)、Request管理上下文分析
1.DBUtils(pymysql数据连接池) import pymysql from DBUtils.PooledDB import PooledDB POOL = PooledDB( creato ...
- flask之基于DBUtils实现数据库连接池、本地线程、上下文
本篇导航: 数据库连接池 本地线程 上下文管理 面向对象部分知识点解析 1.子类继承父类__init__的三种方式 class Dog(Animal): #子类 派生类 def __init__(se ...
- MySQL数据库报错pymysql.err.InterfaceError: (0, '')
今天入库的时候出现了报错pymysql.err.InterfaceError: (0, ''),经过排查,发现是由于把连接数据库的代码放到了插入函数的外部,导致多线程运行出错 def write_in ...
- Python四线程爬取西刺代理
import requests from bs4 import BeautifulSoup import lxml import telnetlib #验证代理的可用性 import pymysql. ...
随机推荐
- (转)Unreal Networking Guide Created by Zach Metcalf
2. 3.
- URAL 1936 Roshambo(求期望)
Description Bootstrap: Wondering how it's played? Will: It's a game of deception. But your bet inclu ...
- ArcGIS Server中创建的两个账户有什么区别
新手常常有这样的疑问: 在安装ArcGIS Server的时候创建的账户和在ArcGIS Server Manager上面创建的账户有什么区别? 解答:前者是是为ArcGIS Server创建的操作系 ...
- 算法(10)Subarray Sum Equals K
题目:在数组中找到一个子数组,让子数组的和是k. 思路:先发发牢骚,这两天做题是卡到不行哇,前一个题折腾了三天,这个题上午又被卡住,一气之下,中午睡觉,下午去了趟公司,竟然把namespace和cgr ...
- Jira & filter & subscribe & issues
Jira & filter & subscribe & issues https://confluence.atlassian.com/search/?query=subscr ...
- WebService使用介绍(一)
Socket实现 javaSocket通信原理 第一步:服务端创建serverSocket,启动服务.监听端口 /** * 天气查询服务端 * @author SMN * @version V1.0 ...
- sessionStorage的用法总结
sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁.因此sessionStorage不是一种持久化的本地 ...
- C#中构造函数和析构函数的用法
构造函数与析构函数是一个类中看似较为简单的两类函数,但在实际运用过程中总会出现一些意想不到的运行错误.本文将较系统的介绍构造函数与析构函数的原理及在C#中的运用,以及在使用过程中需要注意的若干事项.一 ...
- [洛谷P4001][BJOI2006]狼抓兔子
题目大意:给你一个n*m的网格图,有三种边,横的,纵的和斜的,要你求出它的最小割 题解:网络流 卡点:1.无向图,反向弧容量应和正向弧相同 C++ Code: #include<cstdio&g ...
- Android-使用ViewFlipper实现轮番切换广告栏
所谓的轮番切换广告栏,指的是下面这个东西,笔主不知道该怎么确切描述这货... 笔主没有百度研究过其他大牛是怎么实现这个功能的,在这里笔主充分发挥DIY精神,利用ViewFlipper闭门土制了一个,下 ...