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

如何在discord.py中从MySQL提取ELO数据作为变量使用

解决方案

你需要解决两个核心问题:规避SQL注入风险和正确提取数据库中的ELO值,以下是具体修改方案:

1. 替换不安全的SQL写法

不要用f-string直接拼接用户ID到SQL语句中,这会引发SQL注入漏洞,改用参数化查询:

cursor.execute("SELECT ELO from users where ID = %s", (ctx.author.id,))

2. 从查询结果中提取ELO变量

因为你初始化cursor时设置了dictionary=True,fetchall()返回的是字典列表,每个字典对应一行数据,直接通过键名'ELO'即可获取值:

rows = cursor.fetchall()
if rows:  # 先判断是否查询到用户数据
    elo = rows[0]['ELO']  # 用户ID唯一,取第一行数据即可,无需循环
else:
    elo = 0  # 用户不存在时设置默认ELO值

3. 修正Embed字段的使用方式

add_field方法至少需要name和value两个参数,你原代码缺少value参数,同时把ELO值放到合理位置:

完整修改后的代码

@bot.command()
async def bal(ctx):
    # 参数化查询,避免SQL注入
    cursor.execute("SELECT ELO from users where ID = %s", (ctx.author.id,))
    rows = cursor.fetchall()
    
    # 处理查询结果
    elo = rows[0]['ELO'] if rows else 0
    
    # 构建Embed消息
    embedis = discord.Embed(
        title="・                       ZELL | Professional League | User Profile                          ・",
        description=f"<@{ctx.author.id}> Personal Info",
        color=0xc27c0e
    )
    embedis.add_field(name="Rank Statistics:", value=f"ELO: {elo}", inline=True)
    
    await ctx.send(embed=embedis)

额外说明

  • 无需循环rows:用户ID在数据库中应唯一,直接取rows[0]就能拿到当前用户的数据
  • 必须用参数化查询:防止恶意用户构造特殊ID执行恶意SQL语句
  • 增加空结果判断:避免因用户不存在导致后续代码报错

内容的提问来源于stack exchange,提问作者Zell-League Psiclone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:50:24