c# - SQL数据读取器读取不一致

标签 c# sql sqldatareader

我有以下 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。当我运行程序时,数据读取器会跳过循环。但是,如果我在组合框中选择不同的查询,数据读取器将正常工作

最佳答案

您似乎忘记将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)
  {
  }

这意味着“忽略所有错误并继续”。

关于c# - SQL数据读取器读取不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32227703/

相关文章:

c# - C#.NET 中的 DDD "Module"

sql - 分离从postgres中的函数返回的记录

c# - 仅强制从 DataReader 返回单行

c# - SQLDataReader 行计数

c# - SqlDataReader 性能 List<string[]> 或 List<object[]>

c# - 截至目前,使用 COM 对象的正确方法是什么?

c# - "IOException: Cannot locate resource X"在自定义控件中,但应用程序可以运行

c# - 使用 Azure SQL Server 创建 Web API

php - 根据最大日期过滤结果

sql - Oracle中如何查看索引是否被使用