C#数据集的使用顺序是什么?

时间:2015-01-30 15:55:55

标签: c# ado.net

假设这段代码:

//Query the Reports table to find the record associated with the selected report
using (SqlCommand cmd = new SqlCommand("SELECT * FROM VW_MOS_DPL_AccountValidation 
                                 WHERE CLIENT_ID =  '" + txtClientID.Text + "'", con))
   {
       con.Open();
       using (SqlDataReader DT1 = cmd.ExecuteReader())
       {
           // If the SQL returns any records, process the info
           if (DT1.HasRows)
              {
                  while (DT1.Read())
                  {
                      try
                          {
                             int TaskID = Convert.ToInt32(ddlTask.SelectedValue);
                             Label2.Text = (DT1["CUST_NM"].ToString());

我的问题是,如果

"SELECT * FROM VW_MOS_DPL_AccountValidation 
    WHERE CLIENT_ID =  '" + txtClientID.Text + "'"

返回一个包含25条记录的记录集,Label2.Text将填充SQL返回的第一条记录中的数据,还是返回的最后一条记录?

4 个答案:

答案 0 :(得分:4)

SQL中的集合是无序的,除非您明确地对它们进行排序。由于数据是无序的,因此标签将有效地从集合中获得一个随机元素,因此无论是第一个还是最后一个都不是真正相关的。

那就是说,既然你要覆盖结果中每个项目的值,那么当整个操作完成时,它将包含结果中的最后一项,而不是第一项,即使你不知道最后一项是什么将没有order by电话。

答案 1 :(得分:1)

它将填充来自每个记录的数据,即在每个循环迭代中被替换,但最后,它将具有来自最后记录的数据。

按照你的方式去做是没有意义的。更有意义的是,如果你有一个网格控件或其他类型的复合控件,你希望网格的每一行都包含查询中的值或b。)限制你的查询只返回一个结果并使用该结果填充您的单个标签。

此外,我觉得有必要指出一些非常重要,因为您现在拥有它,但是您的查询有问题。您的查询易受SQL注入攻击,正如Scott Chamberlain在其评论中提到的那样。而不是这样做:

new SqlCommand("SELECT * FROM VW_MOS_DPL_AccountValidation 
                                 WHERE CLIENT_ID =  '" + txtClientID.Text + "'", con)

你应该这样做:

new SqlCommand("SELECT * FROM VW_MOS_DPL_AccountValidation WHERE CLIENT_ID = @ID", con)
cmd.Parameters.Add(new SqlParameter("@ID", txtClientID.Text));

答案 2 :(得分:1)

将为数据集中的每一行设置。所以最后,它将具有最后一行的值。

答案 3 :(得分:1)

为什么不通过 将 订单添加到查询中,然后选择第1项? 没有必要获取所有记录才能获得最后一个记录。

using (SqlCommand cmd = new SqlCommand(
  @"  select CUST_NM 
        from VW_MOS_DPL_AccountValidation 
       where CLIENT_ID = @PRM_CLIENT_ID
    order by CUST_NM -- if you want to reverse add 'desc'", 
  con)) {

  con.Open();

  // Do not hardcode - use parameters 
  cmd.Parameters.AddWithValue(@PRM_CLIENT_ID, txtClientID.Text);

  using (SqlDataReader DT1 = cmd.ExecuteReader()) {
    // DT1.HasRows redundant - DT1.Read() returns true if record is read
    if (DT1.Read()) {
      int TaskID = Convert.ToInt32(ddlTask.SelectedValue);
      Label2.Text = (DT1["CUST_NM"].ToString()
    }
  }
}