discord.py操作MySQL更新time_estimation_4表Mod_on字段失败求助
问题排查与修复方案
你代码里存在4处直接导致功能异常的问题:
- 执行Mod_on字段查询时变量名写错:你定义的查询语句是
sql1,但实际执行时传的是sql(这是你之前建表用的语句变量),执行了错误的SQL自然拿不到正确的Mod_on值,所以打印结果为None。 fetchone()返回的是元组类型,哪怕只查单个字段,返回结果也是(0,)或(1,)格式,你直接和整数0/1判断相等永远不成立,更新逻辑根本不会触发。- 你只定义了UPDATE更新语句
sql2,但没有执行cur.execute(sql2),也没有调用db.commit()提交变更,哪怕条件判断正确也不会修改数据库内容。 - 混用f-string拼接SQL和参数化查询,存在SQL注入风险,建议所有数据库操作都使用参数化写法。
修复后代码示例
@pro.command() async def online(ctx): user_id = ctx.author.id # 优先用参数化查询,避免SQL注入 cur.execute('SELECT mod_id FROM time_estimation_4 WHERE mod_id = %s', (user_id,)) out_user = cur.fetchone() if out_user is None: cur.execute('INSERT INTO time_estimation_4 (mod_id) VALUES (%s)', (user_id,)) db.commit() # 查Mod_on字段,执行正确的SQL cur.execute('SELECT Mod_on FROM time_estimation_4 WHERE mod_id = %s', (user_id,)) out = cur.fetchone() # 取元组第一个元素做判断 mod_on_status = out[0] if out else 0 print(mod_on_status) if mod_on_status == 1: await ctx.send("mod's already online") elif mod_on_status == 0: # 执行更新语句并提交 cur.execute('UPDATE time_estimation_4 SET Mod_on = 1 WHERE mod_id = %s', (user_id,)) db.commit() await ctx.send("Done! You won't be recieving notifications and time estimation will be longer!" )
内容的提问来源于stack exchange,提问作者Pew
相关产品推荐
相关产品推荐

