mysql超过最大连接数

!!!!!!!!!!!!!!!!!!!!!!!!

游标记得关闭!!!!

游标记得关闭!!!!

游标记得关闭!!!!

仅仅关闭数据库是不行的,需要先关闭游标再关闭数据库!!!

!!!!!!!!!!!!!!!!!!!!!!!!

道友切记啊!!!!!!!!!!!!!!!!!!!

 

 

 

最近部署了一个项目,经过一段时间发现了些问题。

在运行一段时间后,会出现超过最大连接数的错误,于是针对这个方面进行了一些了解。

以下解释基于个人理解以及项目情况,有不对的地方希望大家指出。

首先使用的是pymysql模块,业务代码无误,数据库也进行了close操作。

按照理想的情况推测,链接-关闭,往复循环,虽然会出现连接数增加的情况,在insert,undate,delete等操作后会关闭连接,

但是结果不尽人意

一度连接数高达几百个,然而在本地测试连接数并不多。

 

 

在不考虑修改任何配置文件的情况下(公用的服务器,不太能重启或者修改等操作)

1.可以考虑多条sql,批量执行

cursor.executemany(sql,data)

2.也可以考虑使用链接池来限制链接数

 

 

下面放一下,监听连接数的代码:

import pymysql
import time

sum = 0

while True:
    #open db connection
    db = pymysql.connect(host="",user="",password="",database='')
    
    #use cursor()
    cursor = db.cursor()
    
    #use execute() run sql
    cursor.execute("show variables like '%max_connections%';")
    
    #USE fetchone()
    Max = cursor.fetchone()
    
    cursor.execute("show global status like 'Max_used_connections';")
    History_max = cursor.fetchone()
    
    cursor.execute("show global status like 'Threads_connected';")
    Currently = cursor.fetchone()
    
    sum = sum + 1
    print("\n--------------------------------\n")
    print("统计日期 :",time.strftime('%Y-%m-%d %H:%M:%S'))
    print("当前统计次数 :",sum)
    print("mysql最大连接数 :",Max[1])
    print("mysql历史最大连接数 :",History_max[1])
    print("mysql当前最大连接数 :",Currently[1])

    cursor.close()
    db.close()
    time.sleep(5)

 

posted @ 2022-01-04 16:05  黑山老道  阅读(296)  评论(0编辑  收藏  举报