You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python处理长时SQL进程报错:tuple对象无get属性

解决pymysql查询SHOW PROCESSLIST时的AttributeError错误

错误原因

pymysql默认游标返回的是**元组(tuple)**类型数据,而非字典,所以调用item.get('Time')这类字典方法会直接报错——元组没有get属性。

修复方案

以下两种方案都能解决问题,按需选择:

方案1:通过元组索引访问字段

SHOW PROCESSLIST返回的字段固定顺序为:Id, User, Host, db, Command, Time, State, Info,直接用索引取值即可:

import pymysql

def main():
    connection = pymysql.connect(user='', password='',
                                 host='',
                                 port=3306,
                                 database='')
    try:
        with connection.cursor() as cursor:
            cursor.execute('SHOW PROCESSLIST')
            for item in cursor.fetchall():
                # Time对应索引5,Command对应索引4
                if item[5] > 3600 and item[4].lower() == 'query':
                    _id = item[0]
                    print(f'正在终止进程ID: {_id}')
                    cursor.execute(f'KILL {_id}')
        connection.commit()
    finally:
        connection.close()

main()

方案2:使用字典游标(DictCursor)

指定游标类型为DictCursor,让查询结果直接返回字典,即可用键名或get()方法访问字段:

import pymysql
from pymysql.cursors import DictCursor

def main():
    connection = pymysql.connect(user='', password='',
                                 host='',
                                 port=3306,
                                 database='',
                                 cursorclass=DictCursor)  # 指定字典游标类型
    try:
        with connection.cursor() as cursor:
            cursor.execute('SHOW PROCESSLIST')
            for item in cursor.fetchall():
                if item['Time'] > 3600 and item['Command'].lower() == 'query':
                    _id = item['Id']
                    print(f'正在终止进程ID: {_id}')
                    cursor.execute('KILL %s', (_id,))
        connection.commit()
    finally:
        connection.close()

main()

额外提示

  • 记得添加connection.commit(),确保KILL操作生效
  • Command字段值默认是大写(如Query),转小写后比较能避免大小写匹配问题
  • 用try...finally包裹逻辑,保证数据库连接一定会关闭,避免资源泄漏
  • 代码中未用到的mysql.connector和json库可以直接删除,精简代码

内容的提问来源于stack exchange,提问作者Nishant Piyush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:30:56