# -*-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. GraphSAGE 代码解析(二) - layers.py

    原创文章-转载请注明出处哦.其他部分内容参见以下链接- GraphSAGE 代码解析(一) - unsupervised_train.py GraphSAGE 代码解析(三) - aggregator ...

  2. ipfs01

    IPFS音乐播放器 IPFS相关 IPFS第一次亲密接触 什么是IPFS IPFS对比HTTP/FTP等协议的优势 IPFS应用场景 ​ ipfs入门 官网地址:https://ipfs.io 下载安 ...

  3. HDU 4467 Graph(图论+暴力)(2012 Asia Chengdu Regional Contest)

    Description P. T. Tigris is a student currently studying graph theory. One day, when he was studying ...

  4. Daily Scrum02 12.05

    deadline果然是第一生产力...这学期一下子4~5个大的Project.然后截止日期都在近期.所有的组员都很辛苦!大家加油~ 这个scrum是当天过后一天补上的.因为当前负责的同学正在忙于编译大 ...

  5. sql between and 边界问题

    1.不同的数据库对 BETWEEN...AND 操作符的处理方式是有差异的.需要自己测试 2.一般情况下.SQL Server中 between and是包括边界值的,not between不包括边界 ...

  6. Java空指针异常解决方法

    Throwable是所有错误或异常的超类,只有当对象是这个类的实例时才能通过Java虚拟机或者Java throw语句抛出. 当Java运行环境发出异常时,会寻找处理该异常的catch块,找到对应的c ...

  7. ai学习记录

    界面:多个预编辑区:制作图形,使用的图形放到工作区内,不使用在预编区.没有Ctrl/Alt+delete的概念,没有前后景颜色.新建:分辨率:矢量软件和分辨率无关: 新建时候不要勾选对齐到像素网格 存 ...

  8. NIO Q&A(持续补充。。。。)

    Q:NIO是非阻塞的.但调用的selector.select()方法会阻塞.这和NIO非阻塞岂不是矛盾了? A:非阻塞指的是 IO 事件本身不阻塞,但是获取 IO 事件的 select 方法是需要阻塞 ...

  9. poj 1034 The dog task (二分匹配)

    The dog task Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 2559   Accepted: 1038   Sp ...

  10. [zoj] 3496 Assignment || 有源汇上下界最大流

    原题 贴个博客吧 #include<cstdio> #include<algorithm> #include<cstring> #define N 510 #def ...