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. ...
随机推荐
- LeetCode 234——回文链表
1. 题目 请判断一个链表是否为回文链表. 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1->2->2->1 输出: true 进阶: 你能否用 O( ...
- eth day05
智能合约众筹实战 淘宝众筹,京东众筹 https://izhongchou.taobao.com/index.htm 分析商业模式 解决京东众筹的痛点 https://izhongchou.taoba ...
- vue实战(一):利用vue与ajax实现增删改查
vue实战(一):利用vue与ajax实现增删改查: <%@ page pageEncoding="UTF-8" language="java" %> ...
- Week1 Team Homework #1 from Z.XML-项目选择思路--基于对曾经大作业项目的思考
这两天试玩了一下去年学长的满分工程<shield star>游戏,再结合了一下他们团队的博客记录,有一种非常牛逼的感觉.具体对于这款游戏的一些思考和看法,毛大神已经说的很好了.因此,这里主 ...
- java笔试面试01
今天给大家分享一下小布去广州华南资讯科技公司笔试和面试的过程. 过程:1.HR面试 2.笔试 3.技术面试 小布下午两点到达,进门从前台领了一张申请表,填完之后带上自己的简历到4楼就开始HR面试. ...
- pptp协议的工作原理
我的工作机是A,通信网卡是Aeth0, Appp0: 然后我的云主机是B, 通信的网卡是Beth0, Bppp0: 在网卡Bppp0上会不断地很清晰的数据包: 16:40:39.522917 IP 6 ...
- SMT(SF)
示例一: uint iPwmDuty; double temp; temp = (double)AdConvert(AN_TEMPERATURE); temp = temp/; iPwmDuty = ...
- 【bzoj2064】分裂【压状dp】
Description 背景: 和久必分,分久必和... 题目描述: 中国历史上上分分和和次数非常多..通读中国历史的WJMZBMR表示毫无压力. 同时经常搞OI的他把这个变成了一个数学模型. 假设中 ...
- 移动端H5滚动穿透解决方案
最近遇到一个很 巨恶心的问题 ios10下面 页面弹窗有滚动穿透问题 各种google 终于找到了答案,但是体验还不是很好,基本能忍受 废话不多说,上方法 最后终于想到一个处理方案,就是第一种方案的 ...
- 正确答案 [Hash/枚举]
正确答案 题目描述 小H与小Y刚刚参加完UOIP外卡组的初赛,就迫不及待的跑出考场对答案. "吔,我的答案和你都不一样!",小Y说道,"我们去找神犇们问答案吧" ...