2

我正在使用 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

4

1 回答 1

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'))
于 2019-09-21T20:44:12.613 回答