pymysql创建连接池连接mysql

在这里只介绍实际应用中会用到的连接池来创建与mysql的数据库连接

面对大量的web请求和插入与查询请求,单个的mysql连接会不稳定,针对错误Lost connection to MySQL server during query ([Errno 104] Connection reset by peer)

优势:在程序创建连接的时候从一个空闲的连接中获取,不需要重新初始化连接,提升获取连接的速度

DBUtils是Python的一个用于实现数据库连接池的模块,同时使用第三方库pymysql,这里有个坑点需要注意:python3暂不适配DBUtils2和3,建议使用DBUtils1.3版本

pip install DBUtils==1.3

pip install pymysql

代码如下:

import pymysql
from DBUtils.PooledDB import PooledDB

pool = PooledDB(pymysql,
                host='localhost',
                port=3306, # 注意是int
                user='root',
                password='root',
                db='news_sys',
                charset='utf8', # 注意不是utf-8
                autocommit=True, # pymysql对于数据的增删改默认是不会自动提交的,需要手动的conn.commit()才会真正修改提交,将autocommit 设置为True就可以免除手动的commit
                cursorclass=pymysql.cursors.DictCursor # 默认返回sql查询结果为((),()...),此处修改为[{},{}...]
                )
conn = pool.connection()
cur = conn.cursor()
sql = 'select * from t_user'
cur.execute(sql)
results = cur.fetchall() # 还有fetchone()/fetchmany(n)等方法,都是见名知意的
print(results)
for i in results:
    print(i)
conn.close()

Output:

[{'id': 2, 'type': '体育'}, {'id': 5, 'type': '历史'}, {'id': 4, 'type': '娱乐'}, {'id': 3, 'type': '科技'}, {'id': 1, 'type': '要闻'}]
{'id': 2, 'type': '体育'}
{'id': 5, 'type': '历史'}
{'id': 4, 'type': '娱乐'}
{'id': 3, 'type': '科技'}
{'id': 1, 'type': '要闻'}
posted @ 2022-05-11 13:52  少年不太冷2  阅读(638)  评论(0)    收藏  举报