# -*-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的更多相关文章

  1. 杂项之pymysql连接池

    杂项之pymysql连接池 本节内容 本文的诞生 连接池及单例模式 多线程提升 协程提升 后记 1.本文的诞生 由于前几天接触了pymysql,在测试数据过程中,使用普通的pymysql插入100W条 ...

  2. 第一篇:杂项之pymysql连接池

    杂项之pymysql连接池   杂项之pymysql连接池 本节内容 本文的诞生 连接池及单例模式 多线程提升 协程提升 后记 1.本文的诞生 由于前几天接触了pymysql,在测试数据过程中,使用普 ...

  3. Day12 线程池、RabbitMQ和SQLAlchemy

    1.with实现上下文管理 #!/usr/bin/env python# -*- coding: utf-8 -*-# Author: wanghuafeng #with实现上下文管理import c ...

  4. python运维开发(十二)----rabbitMQ、pymysql、SQLAlchemy

    内容目录: rabbitMQ python操作mysql,pymysql模块 Python ORM框架,SQLAchemy模块 Paramiko 其他with上下文切换 rabbitMQ Rabbit ...

  5. 3、flask之基于DBUtils实现数据库连接池、本地线程、上下文

    本篇导航: 数据库连接池 本地线程 上下文管理 面向对象部分知识点解析 1.子类继承父类__init__的三种方式 class Dog(Animal): #子类 派生类 def __init__(se ...

  6. python全栈开发day113-DBUtils(pymysql数据连接池)、Request管理上下文分析

    1.DBUtils(pymysql数据连接池) import pymysql from DBUtils.PooledDB import PooledDB POOL = PooledDB( creato ...

  7. flask之基于DBUtils实现数据库连接池、本地线程、上下文

    本篇导航: 数据库连接池 本地线程 上下文管理 面向对象部分知识点解析 1.子类继承父类__init__的三种方式 class Dog(Animal): #子类 派生类 def __init__(se ...

  8. MySQL数据库报错pymysql.err.InterfaceError: (0, '')

    今天入库的时候出现了报错pymysql.err.InterfaceError: (0, ''),经过排查,发现是由于把连接数据库的代码放到了插入函数的外部,导致多线程运行出错 def write_in ...

  9. Python四线程爬取西刺代理

    import requests from bs4 import BeautifulSoup import lxml import telnetlib #验证代理的可用性 import pymysql. ...

随机推荐

  1. Spring实战第一章学习笔记

    Spring实战第一章学习笔记 Java开发的简化 为了降低Java开发的复杂性,Spring采取了以下四种策略: 基于POJO的轻量级和最小侵入性编程: 通过依赖注入和面向接口实现松耦合: 基于切面 ...

  2. 最大流——EK算法

    一.算法理论 [基本思想] 反复寻找源点s到汇点t之间的增广路径,若有,找出增广路径上每一段[容量-流量]的最小值delta,若无,则结束.在寻找增广路径时,可以用BFS来找,并且更新残留网络的值(涉 ...

  3. 将EXCEL表中的数据轻松导入Mysql数据表

    转载自:http://blog.163.com/dielianjun@126/blog/static/164250113201042310181431/ 在网络上有不较多的方法,在此介绍我已经验证的方 ...

  4. 山科SDUST OJ Problem J :连分数

    Problem J: 连分数 Time Limit: 1 Sec  Memory Limit: 64 MBSubmit: 2723  Solved: 801[Submit][Status][Web B ...

  5. linux服务器su之后变成bash-4.1#

    当前为root权限 cd /home/jboss 执行如下命令,将缺失的配置文件拷贝到指定位置即可 cp ./.bashrc /root cp ./.bash_profile /root 然后切换账号 ...

  6. java线程(5)——线程池(上)

    引入: 在之前的例子中,我们需要使用线程时就直接去创建一个线程,这样既不浪费资源又十分方便.但如果我们需要创建多个并发的线程,而且短时间执行就结束了,如果还用之前的方式,就会大大降低效率和性能了. 因 ...

  7. union的代码有点难理解额

    union跟位域都可以节省内存,而且union在某些地方还能起到更好看的效果? 比如: struct Matrix { union { struct { float _f11, _f12, _f13, ...

  8. httpclient upload file

    用httpclient upload上传文件时,代码如下: HttpPost httpPost = new HttpPost(uploadImg); httpPost.addHeader(" ...

  9. 【bzoj1018】[SHOI2008]堵塞的交通traffic 线段树区间合并+STL-set

    题目描述 给出一张2*n的网格图,初始每条边都是不连通的.多次改变一条边的连通性或询问两个点是否连通. 输入 第一行只有一个整数C,表示网格的列数.接下来若干行,每行为一条交通信息,以单独的一行“Ex ...

  10. P1712 [NOI2016]区间

    题目描述 在数轴上有 NN 个闭区间 [l_1,r_1],[l_2,r_2],...,[l_n,r_n][l1​,r1​],[l2​,r2​],...,[ln​,rn​] .现在要从中选出 MM 个区 ...