【问题标题】:SQL datareader reading inconsistentlySQL 数据读取器读取不一致
【发布时间】:2015-08-26 13:15:29
【问题描述】:

我在 C# 中有以下代码-

private void sendnotificationmail(string enqid)
{
    try
    {
        connection.Open();
        List<string> maillist = new List<string>();
        string sql = "SELECT     TrussLog.repmail, TrussLog.branchemail, TrussEnquiry.DesignerEmail FROM         TrussLog FULL OUTER JOIN                      TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID         where TrussEnquiry.Enquiry_ID = '" + enqid + "'";
        SqlCommand cmd = new SqlCommand(sql);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            if (!string.IsNullOrEmpty(reader[0].ToString()))
            {
                maillist.Add(reader[0].ToString());
            }
            if (!string.IsNullOrEmpty(reader[1].ToString()))
            {
                maillist.Add(reader[1].ToString());
            }
            if (!string.IsNullOrEmpty(reader[2].ToString()))
            {
                maillist.Add(reader[2].ToString());
            }
        }
        connection.Close();

        if (result != DialogResult.Cancel)
        {
            processmail(maillist);
        }
    }
    catch (Exception)
    {
    }
}

我从 Windows 窗体上的组合框中获取变量 enqid 的值。组合框的内容是从数据库中检索的。在表单加载时,组合框会显示从数据库中检索到的第一个 enquiryID。当我运行我的程序时,数据阅读器会跳过循环。但是,如果我在组合框中选择不同的查询,数据阅读器将正常工作

【问题讨论】:

  • 第一个enquiryId 可能没有结果。您当前的代码暴露于 SQL 注入。请改用参数化查询。
  • 从数据库中检索到第一个enquiryID
  • 为什么会有一个空捕获?删除它并重新测试。
  • 一个 SQL 注入漏洞和一个空的 catch 块。这应该使得在 IDE 之外进行几乎不可能的调试......
  • @David 并且不要忘记只有在没有错误的情况下才会关闭连接:using 块丢失。

标签: c# sql sqldatareader


【解决方案1】:

您似乎忘记将CommandConnection关联

  // SendNotificationMail is more readable then sendnotificationmail
  private void sendnotificationmail(string enqid) {
    // put IDisposable into using...
    using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
      con.Open();

      using (SqlCommand cmd = new SqlCommand()) {
        cmd.Connection = con; // <- You've omitted this

        // have SQL readable
        cmd.CommandText =
          @"SELECT TrussLog.repmail, 
                   TrussLog.branchemail, 
                   TrussEnquiry.DesignerEmail 
              FROM TrussLog FULL OUTER JOIN                      
                   TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID         
             WHERE TrussEnquiry.Enquiry_ID = @prm_Id";

        // use parametrized queries
        cmd.Parameters.AddWithValue("@prm_Id", enqid);

        using (SqlDataReader reader = cmd.ExecuteReader()) {
          while (reader.Read()) {
            ...
          }
        }
      }
    }
  }

从不从不写代码一样

  catch (Exception)
  {
  }

意思是“忽略所有错误并继续”。

【讨论】:

  • 然后 catch 吞下了错误。为什么人们认为抑制错误可以修复它们?!从来不明白。
  • @DmitryBychenko 是的,你说得对,他没有定义与命令的连接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多