Discord bancheck命令MySQL参数错误:int类型参数不被支持
错误原因
你的代码触发错误的核心是参数格式不合法:
- 你写的
val = (ban_id)并不是Python元组,括号仅作为优先级符号使用,最终val还是单个整数类型。 - mysql-connector的
execute()方法要求第二个参数必须是元组、列表或字典类型,用于传递SQL占位符的参数值。
修复方案
只需将参数包装成合法的元组(注意末尾必须加逗号)或列表即可:
方案1:使用元组(推荐)
修改参数定义行:
sql = "SELECT user_id, reason FROM bans WHERE ban_id = %s" val = (ban_id,) # 末尾添加逗号,确保这是一个单元素元组 mycursor.execute(sql, val)
方案2:使用列表
如果更习惯列表语法,也可以这样写:
sql = "SELECT user_id, reason FROM bans WHERE ban_id = %s" val = [ban_id] mycursor.execute(sql, val)
额外优化建议
为了避免数据库资源泄漏和异常情况,建议用with语句管理连接和游标,同时增加异常捕获:
@commands.slash_command(name="bancheck", description="Checks the database for an ban.") async def bancheck(self, ctx, ban_id: int): try: with mysql.connector.connect( host=config.host, user=config.user, password=config.password, database=config.database ) as mydb: with mydb.cursor() as mycursor: sql = "SELECT user_id, reason FROM bans WHERE ban_id = %s" val = (ban_id,) mycursor.execute(sql, val) result = mycursor.fetchone() message = f"The user with ID {result[0]} was banned for '{result[1]}'" if result else "No ban was found with that ID." embed = discord.Embed(title="Ban Check", description=message, color=discord.Color.red()) embed.add_field(name="Ban ID", value=f"{ban_id}", inline=False) await ctx.respond(embed=embed) except mysql.connector.Error as e: await ctx.respond(f"数据库查询失败:{str(e)}")
内容的提问来源于stack exchange,提问作者Knife worm
相关产品推荐
相关产品推荐

