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

discord.py开发遇Python 'guild' cannot be converted to a MySQL type错误如何解决

问题修复方案

错误根因

  • 报错提示Python 'guild' cannot be converted to a MySQL type是因为你在INSERT、UPDATE语句里传入了ctx.guild,这是discord.py定义的Guild类对象,MySQL无法识别这种自定义对象,你需要传入的是服务器的数字ID,也就是ctx.guild.id(你之前注释掉的写法是正确的)
  • INSERT语句中的字段名拼写错误,你写的channel_i应该是channel_id,和你SELECT查询时用的字段名保持一致
  • 你每次执行完命令都关闭了全局的数据库连接db和游标cursor,后续再调用这个命令会因为连接已关闭触发新的报错,不要在单次命令的逻辑里关闭全局数据库连接,或者每次操作前重新建立连接。

修复后的代码

@welcome.command()
@has_permissions(administrator=True)
async def channel(self, ctx, channel:discord.TextChannel):
    # 原f-string拼接SQL存在注入风险,统一改成参数化查询
    cursor.execute('SELECT channel_id FROM welcome WHERE guild_id = %s', (ctx.guild.id,))
    result = cursor.fetchone()
    if result is None:
        # 修正字段名和guild_id参数
        cursor.execute('INSERT INTO welcome (guild_id, channel_id) VALUES (%s,%s)', (ctx.guild.id, channel.id))
        db.commit()
        await ctx.send(f'欢迎频道已设置为 {channel.mention}')
    else:
        # 修正guild_id参数
        cursor.execute('UPDATE welcome SET channel_id = %s WHERE guild_id = %s', (channel.id, ctx.guild.id))
        db.commit()
        await ctx.send(f'欢迎频道已更新为 {channel.mention}')
    # 仅关闭游标,不要关闭全局数据库连接
    cursor.close()

额外提示:所有SQL操作都建议使用参数化查询的写法,不要直接用f-string拼接用户可控的参数,避免被恶意构造的内容触发SQL注入漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:15:06