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. ...
随机推荐
- ThreadPool线程池的几种姿势比较
from multiprocessing.pool import ThreadPool #from multiprocessing.dummy import Pool as ThreadPool #这 ...
- LeetCode 全解(bug free 训练)
1.Two Sum Given an array of integers, return indices of the two numbers such that they add up to a s ...
- eclipse 创建Makefile工程生成多个执行文件
1.创建Makefile工程 2.创建inc src Debug 目录 用于存放头文件源文件 3.编写Makefile 需要在有源文件的目标天剑Makefile文件,如下给出一个生成两个target的 ...
- UVA 11884 A Shooting Game(记忆化搜索)
A and B are playing a shooting game on a battlefield consisting of square-shaped unit blocks. The bl ...
- shell 中的expect 用法
expect一般用于实现用脚本来自动远程登录,对远程机器执行相关操作 测试机上的expect目录一般在/usr/bin/expect路径 下面是从网上查询的用法总结: 1. expect中的判断语句: ...
- Python不同进制之间的转换
不同的进制 二进制 0b101 以数字0和字母b打头的表示二进制数 如果出现大于等于2的数 会抛出SyntaxError异常 八进制 0711 以数字0打头的数字表示八进制数 如果出现大于 ...
- vue-cli配置jquery 以及jquery第三方插件
只使用jquery: 1. cnpm install jquery --save 2. cnpm install @types/jquery --save-dev (不使用ts的不需要安装此声明 ...
- 域名/网站名/URL
http://mail.163.com/index.html 1)http://:协议,也就是HTTP超文本传输协议,网页在网上传输的协议. 2)mail:服务器名,代表着是一个邮箱服务器,所以是ma ...
- spring笔记二
DI—Dependency Injection,即“依赖注入”:组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中.依赖注入的目的并非为软件系统带来更多功能,而是 ...
- 【bzoj1878】[SDOI2009]HH的项链 树状数组
题目描述 HH有一串由各种漂亮的贝壳组成的项链.HH相信不同的贝壳会带来好运,所以每次散步完后,他都会随意取出一段贝壳,思考它们所表达的含义.HH不断地收集新的贝壳,因此, 他的项链变得越来越长.有一 ...