【问题标题】:C# MySQL reader is not readingC# MySQL 阅读器不阅读
【发布时间】:2018-03-15 20:28:33
【问题描述】:

我有一个从指定列读取值的函数。它看起来像这样:

        private bool OpenConnection() // Just opens the connection. No error here.
        {
            try
            {
                conn.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Connection not opened");
                return false;
            }
        }
    private void getStats(string user, string cate, string score)
    {
        if (OpenConnection())
        {
            try
            {
                string getuserstats = $"SELECT {cate} FROM scores WHERE user = '{user}'";
                MySqlCommand cmd = new MySqlCommand(getuserstats, conn);
                MySqlDataReader getscore = cmd.ExecuteReader();
                MessageBox.Show(getscore.Read().ToString()); //outputs false.
                while(getscore.Read())//does not run
                {
                    MessageBox.Show("Reading!");//does not run
                    score = getscore.GetString(0);//does not run
                    MessageBox.Show(score); //does not run
                }
                getscore.Close();
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error getting scores!");
                conn.Close();
            }
        }
        else
        {
            MessageBox.Show("Connection not opened!");
        }
    }

SQL 命令部分似乎运行良好,我用一些不同的查询对其进行了测试,它们都运行良好。

但是,SQL 阅读器本身似乎没有运行。我也没有收到异常错误。

我使用了一个消息框来显示我的读者阅读的布尔值,它输出了 false。这是为什么呢?

【问题讨论】:

  • 你试过直接在工作台上运行getuserstats 吗?它会给你任何结果吗?
  • 是的。我在工作台上运行了 getuserstats,它运行良好。花括号也适用于其他 sql 代码和阅读器。
  • 使用调试器并检查 user 和 cate 的值是什么。我们无法重现您的情况。该代码在形式上是正确的,尽管它可用于在您的数据库上启动 Sql Injection hack。

标签: c# mysql sqldatareader


【解决方案1】:

Read() 返回 false 的最可能原因是没有记录与您正在执行的查询匹配。您确定该表中有与给定用户名匹配的任何记录吗?并且您正在连接的数据库就是您认为它正在连接的数据库。

这不会相关,但 MySqlCommand 和 MySqlDataReader 都是一次性的,连接也是如此,因此您应该将它们放在“使用”块中,或显式处理它们。

【讨论】:

  • 还值得指出的是,原始代码容易受到 SQL 注入攻击 - user 应该作为参数传递给查询,而不是自己构造字符串.例如,如果 user = "O'Reilly",你的代码就会崩溃。
猜你喜欢
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2017-12-22
  • 2017-06-08
  • 2013-11-24
  • 2017-05-27
相关资源
最近更新 更多