python-3.x - 如何修复“参数必须支持迭代”以在 PyMySQL 输出上制表
问题描述
我正在使用 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
解决方案
我发现这个问题的解决方案最终是我应该使用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'))
推荐阅读
- java - 来自 Spring 数据的 Page 的映射如何工作?
- r - 制作总和列的 R DataTable 解决方案
- python - NameError:名称“高度”未在第 10 行定义
- python - 如何修改 if/else 块以按预期捕获异常?
- ruby-on-rails - 使用 Rails 迁移的表中的两个外键引用另一个表中的一个主键
- javascript - 这个递归函数的操作顺序是什么?
- azure-active-directory - 使用 Azure AD 作为 Azure B2C 的身份验证提供程序
- json - 如何在python中通过多个键过滤json?
- twilio - Twilio Flex - 添加具有受限访问权限的代理,无需单点登录 SSO
- c# - Firebase-realtime-database 如何将嵌套子节点中的数据作为列表返回