如何修复``参数必须支持迭代''以在PyMySQL输出上制表

时间:2019-09-21 17:15:53

标签: python-3.x pymysql tabulate

我正在使用PyMySQL从数据库执行选择查询,我想使用表格来格式化这些查询的输出。当SQL查询仅涉及选择一列时,我已经能够使表正确地工作,但是对于涉及选择多列的查询,我无法将其表化。

我尝试了以下方法:

  • 通过执行headers = ['column name 1','column name 2'...]来明确命名标题
  • 告诉制表使用PyMySQL生成的字典中的键(我使用的是DictCursor,我可以通过执行“ type(result)”来验证输出是否是正确的字典
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

1 个答案:

答案 0 :(得分:0)

我发现此问题的解决方案最终是我应该使用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'))