You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord Bot中for循环调用embed.add_field报TypeError问题求助

错误原因分析

你的核心问题是对数据库fetchall()返回的数据结构理解有误:

  • cursor.fetchall()返回的是元组组成的列表,每个元组代表数据库中的一行记录。比如你查询邮箱和密码两列,结果会是类似[("user1@example.com", "pass123"), ("user2@example.com", "456pass")]的结构。
  • 循环for i in netres中,i是每一行的元组(比如("user1@example.com", "pass123")),但你错误地用i[0](字符串类型的邮箱值)去索引netres[0]这个元组——元组仅支持整数/切片作为索引,因此触发TypeError。
修复代码

直接遍历每一行记录,取出对应位置的字段即可:

方法1:索引取值

for row in netres:
    email = row[0]
    password = row[1]
    embed.add_field(name=f"Email: {email}", value=f"Password: {password}", inline=False)

方法2:元组解包(更简洁)

for email, password in netres:
    embed.add_field(name=f"Email: {email}", value=f"Password: {password}", inline=False)
额外优化提示

如果查询结果列数较多,或想避免索引取值的混淆,可以将每行元组转为字典,通过列名直接取值:

# 获取查询结果的列名
columns = [desc[0] for desc in c.description]
# 将每行元组转为字典
netres_dicts = [dict(zip(columns, row)) for row in netres]

# 遍历字典取值
for item in netres_dicts:
    embed.add_field(name=f"Email: {item['你的邮箱列名']}", value=f"Password: {item['你的密码列名']}", inline=False)

内容的提问来源于stack exchange,提问作者signalmute

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:01:17