首页 > 解决方案 > 如何修复“参数必须支持迭代”以在 PyMySQL 输出上制表

问题描述

我正在使用 PyMySQL 从数据库中执行选择查询,并且我想使用制表来格式化这些查询的输出。当 SQL 查询只涉及选择一列时,我已经能够让制表正常工作,但我无法让制表与涉及选择多列的查询一起工作。

我尝试了以下方法:

displayConfigSummary = "select `Product Line`.`Product Line Name`, `Product Configuration`.`Processor`, `Product Configuration`.`Graphics Card`, `Product Configuration`.`Memory Capacity (GB)`, `Product Configuration`.`Storage Capacity (GB)`  from `Product Line`,`Product Configuration` where `Product Configuration`.`Product Line ID` = `Product Line`.`GUID` and `Product Configuration`.`SKU ID` = %s"

cursor.execute(displayConfigSummary,(configID))

result = cursor.fetchone()

print('Here is your completed configuration:\n')

print(tabulate(result, headers='keys', tablefmt='psql'))

当我调试程序时,我收到错误-: Exception has occurred: TypeError zip_longest argument #4 must support iteration

标签: python-3.xpymysqltabulate

解决方案


我发现这个问题的解决方案最终是我应该使用cursor.fetchall()而不是cursor.fetchone(). 即使 SQL 查询只会产生一行,通过使用 fetchall() 方法,我也可以通过表格来识别列名并将它们打印出来。

displayConfigSummary = "select `Product Line`.`Product Line Name`, `Product Configuration`.`Processor`, `Product Configuration`.`Graphics Card`, `Product Configuration`.`Memory Capacity (GB)`, `Product Configuration`.`Storage Capacity (GB)`  from `Product Line`,`Product Configuration` where `Product Configuration`.`Product Line ID` = `Product Line`.`GUID` and `Product Configuration`.`SKU ID` = %s"

cursor.execute(displayConfigSummary,(configID))

result = cursor.fetchall()

print('Here is your completed configuration:\n')

print(tabulate(result, headers='keys' ,tablefmt='psql'))

推荐阅读