栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

PyMySQL与MySQL连接池相关的知识点

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PyMySQL与MySQL连接池相关的知识点

1. 常规用法

如果使用PyMySQL,常见的方法如下

connection = pymysql.connect(
    host="localhost",
    port=3306,
    database="forest",
    user="root",
    password="123456"
)

with connection.cursor() as cursor:
    print(cursor)
    cursor.execute("select count(*) from user")
    data = cursor.fetchall()
    print(data,)

其中名词的解释如下:

Connection
Representation of a socket with a mysql server.
The proper way to get an instance of this class is to call connect().Establish a connection to the MySQL databaseCursor
This is the object used to interact with the database.
Do not create an instance of a Cursor yourself. Call connections.Connection.cursor(). 2. 连接池用法

连接池指的是应用和数据库的连接池,理论上是应用提前准备好(如启动时)几个和数据库连接好的连接,一直供应用使用,直到应用关闭,省去每次查询时重新连接上数据库和关闭数据库连接的时间。

其中连接池指的即是多个 connection的连接池

具体实践可以使用 DBUtils和 PyMySQL构造连接池

    DBUtils User’s Guide, https://webwareforpython.github.io/DBUtils/main.htmlhttps://github.com/WebwareForPython/DBUtils
2.1 如何查询到连接池

连接上MySQL,通过命令show full processlist即可查询当前连接上MySQL的连接(或即socket连接)

如下,即为通过 Navicat for MySQL 连接上查询出的结果

2.2 构造连接池

通过 DBUtils和 PyMySQL构造连接池的代码如下

import time
import pymysql
from dbutils.pooled_db import PooledDB

pool = PooledDB(pymysql,
                3,  # 默认初始化好3个连接
                host="localhost",
                port=3306,
                database="forest",
                user="root",
                password="123456")
connection = pool.connection()

if __name__ == '__main__':
    print("sleep 30 ...")
    time.sleep(30)

在 Navicat for MySQL 连接上查询出的结果如下(在sleep结束之前),可以看到time=3,即该连接活跃的时间长度

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/740613.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号