前言:当我们发现很多异常连接占用满我们的连接池,而删除他们需要一个个kill非常不方便,所以网上找了一个存过,可以批量根据某个条件进行kill,记录一下。
sql
-- 显示所有的连接
show processlist;
-- 下面是存过的创建
-- 获取所有连接的列表,并选择执行时间超过100秒的连接
DELIMITER //
drop procedure IF EXISTS KillLongRunningQueries;
CREATE PROCEDURE KillLongRunningQueries()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE conn_id INT;
-- 这里改为自己的条件
DECLARE cur CURSOR FOR SELECT id FROM INFORMATION_SCHEMA.PROCESSLIST WHERE state='Sending data' AND USER = 'user01';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO conn_id;
IF done THEN
LEAVE read_loop;
END IF;
-- 执行KILL命令
SET @kill_command = CONCAT('KILL query ', conn_id, ';');
PREPARE stmt FROM @kill_command;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur;
END//
DELIMITER ;
-- 存过结束
-- 调用存储过程来批量删除连接
CALL KillLongRunningQueries();