我正在使用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
答案 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'))