python进行大量sql报错(非连接池问题)

在运行Python程序处理数据库时遇到'Can not connect to MySQL server. Too many connections'错误。问题根源在于数据库语句阻塞,达到MySQL的最大连接数。通过查看并杀死阻塞进程可以暂时解决,但长期解决方案包括减缓SQL执行速度、增加最大连接数或优化数据库设计。文章还提及了使用线程和连接池来管理数据库连接,并提醒注意错误处理和资源释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天跑数据库得时候报出了这个问题:“Can not connect to MySQL server. Too many connections”-mysql 1040

百度了下根本原因是数据库语句阻塞导致达到了MySQL本机得最大连接
只需要杀死这些阻塞得进程即可。

查看所有数据库进程: show processlist##类似于sleep都是当前在阻塞当中

在这里插入图片描述
杀死单个进程:kill id#对应id

那么往往需要你kill得时候一般就是阻塞导致当前进程超过最大值#就报错而言

这时候了使用下面语句查询commit之后循环提交

select concat('KILL ',id,';') from information_schema.processlist where user='root'

详细代码:###修改了下变成线程版得,sql也改了,主要是将全局话得游标和连接改到单个查询或修改##一次掉用即重新构建连接

        def run(self):
        sq = Sql_all()
        global h
        # sql = "select concat('KILL ',id,';') from information_schema.processlist where user='root'"
        # res_s = self.op_select(sql)
        while True:
            if h >= len(res_s):
                break
            with Comparison._instance_lock:
                if self.res_s:

                    h+=1
    
很高兴能回答您的问题。关于Python使用MySQL连接池,可以使用第三方库PyMySQL提供的连接池功能,也可以使用Python标准库中concurrent.futures提供的线程池和进程池来实现。 具体操作可以参考以下代码示例: ``` import pymysql from pymysql import cursors from concurrent.futures import ThreadPoolExecutor, as_completed # 创建连接池 class ConnectionPool(object): def __init__(self, size=10): self.__pool = [] for _ in range(size): conn = pymysql.connect(host='localhost', user='root', password='password', database='test', cursorclass=cursors.DictCursor) self.__pool.append(conn) # 获取连接 def get_conn(self): return self.__pool.pop() # 释放连接 def add_conn(self, conn): self.__pool.append(conn) pool = ConnectionPool() # 使用连接池查询数据 def query(sql): conn = pool.get_conn() cursor = conn.cursor() cursor.execute(sql) result = cursor.fetchall() cursor.close() pool.add_conn(conn) return result # 使用线程池并发查询数据 def main(): sqls = ['SELECT * FROM table1;', 'SELECT * FROM table2;', 'SELECT * FROM table3;'] with ThreadPoolExecutor(max_workers=3) as executor: future_to_sql = {executor.submit(query, sql): sql for sql in sqls} for future in as_completed(future_to_sql): sql = future_to_sql[future] try: result = future.result() except Exception as e: print('%s 报错: %s' % (sql, str(e))) else: print('%s 查询果: %s' % (sql, str(result))) if __name__ == '__main__': main() ``` 以上是使用连接池和线程池来实现MySQL查询操作的示例代码,希望对您有帮助。如果您有其他问题,欢迎继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值