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

MySQL Connector C#中MySqlDataReader.Read()仅返回结果时运行问题求解

问题根因

MySqlDataReader的Read()方法的作用是将游标移动到结果集的下一行,仅当存在下一行数据时返回true,无匹配数据时第一次调用就会返回false,所以循环体自然不会执行,这是组件的正常设计,不属于异常。
另外你原有代码存在逻辑错误:你查询语句已经加了WHERE email = 'xxx'过滤条件,只要进入循环的行,email字段必然等于你传入的参数,循环内的if (email == rdr[0].ToString())判断完全多余,写在对应else分支里的OTA逻辑本身就不可能触发。

修复方案

调整判断逻辑:用标记位记录是否查询到匹配邮箱,循环结束后再根据标记位判断走对应分支,同时修复原有SQL注入漏洞,优化查询性能。
修复后的参考代码如下:

conn.Open();
Debug.Log("SUCCESSFULL CONNECTION!");
if (!isLogin)
{
    Debug.Log("Is not login");
    bool doesEmailExist = false;
    // 改用SELECT 1而非SELECT *,仅做存在性判断时性能更高
    string seecQuery = "SELECT 1 FROM accounts WHERE email = @Email";
    MySqlCommand cmd = new MySqlCommand(seecQuery, conn);
    // 使用参数化查询,避免字符串拼接导致的SQL注入漏洞
    cmd.Parameters.AddWithValue("@Email", email);
    Debug.Log(seecQuery);
    // using语法会自动释放MySqlDataReader资源,避免内存泄漏
    using (MySqlDataReader rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            Debug.Log("Checking to see if the account exists");
            doesEmailExist = true;
            Debug.Log("The account exists");
            accountExists.SetActive(true);
        }
    }
    // 循环结束后统一判断是否存在匹配邮箱
    if (!doesEmailExist)
    {
        Debug.Log("Email is not in use. Starting OTA");
        StartCoroutine(sendOTA());
        OTARead.SetActive(true);
    }
    // 记得用完关闭数据库连接
    conn.Close();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:54:03