繁体   English   中英

SQL查询返回2个结果,但在C#网页中仅显示1个结果

[英]SQL Query returns 2 results but only 1 result showing in c# webpage

我有一张表,它列出了一家公司营业时间的时间表,该表有四列:Id,工作,开始和完成。

Monday     1/1/1900 8:00:00 AM    1/1/1900 5:00:00 PM
Tuesday    1/1/1900 8:00:00 AM    1/1/1900 5:00:00 PM
Wednesday  1/1/1900 8:00:00 AM    1/1/1900 5:00:00 PM
Thursday   1/1/1900 8:00:00 AM    1/1/1900 5:00:00 PM
Friday     1/1/1900 8:00:00 AM    1/1/1900 3:00:00 PM
Saturday   1/1/1900 12:00:00 AM   1/1/1900 12:00:00 AM
Sunday     1/1/1900 12:00:00 AM   1/1/1900 12:00:00 AM

我使用此查询在gridview表中显示了开放时间,并且工作正常。 我得到一张周一至周五显示的表格,以及开放和关闭的时间。

select * from Schedule where [Commencing] != [Finishing];

然后,我创建了一个名为“计划”的类。

public class Scheduling
{
public int Id { get; set; }
public string Working { get; set; }

public Scheduling(int Id, string Working)
{
    this.Id = Id;
    this.Working = Working;
}
}

并更新了我的ConnectionClass如下:

public static ArrayList GetCloseSchedule(string Id)
{
    ArrayList list = new ArrayList();
    string query = string.Format("select * from Schedule where [Commencing] = [Finishing]", Id);

    try
    {
        conn.Open();
        command.CommandText = query;
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            int id = reader.GetInt32(0);
            string Working = reader.GetString(1);

            Scheduling schedules = new Scheduling(id, Working);
            list.Add(schedules);
        }
    }
    finally
    {
        conn.Close();
    }

    return list;
}

然后将其保存在default.aspx.cs文件中。

str = "select * from Schedule where [Commencing] = [Finishing]";
    com = new SqlCommand(str, con);
    ArrayList Scheduling = ConnectionClass.GetCloseSchedule(lblMsgO.Text);

    foreach (Scheduling schedules in Scheduling)
    {
        sb.Append(string.Format(@"{0}<br />",
           schedules.Working));

        lblMsgO.Text = sb.ToString();

        sb.Clear();
        reader.Close();
        con.Close();
    }

这是一个非常简单的查询,我已经成功完成了其中的几个查询,因此我不确定为什么这个查询无法正常工作。 即使我在数据库中测试SQL查询时,两行都出现,它仅显示星期日,而跳过星期六。

在您的default.aspx.cs中,每次循环都会覆盖lblMsg0的值。 您应该在循环之外退出对StringBuilder label和清除的写操作(如果您在每个时间清除StringBuilder值,那么您将失去使用StringBuilder

str = "select * from Schedule where [Commencing] = [Finishing]";
com = new SqlCommand(str, con);
ArrayList Scheduling = ConnectionClass.GetCloseSchedule(lblMsgO.Text);

foreach (Scheduling schedules in Scheduling)
{
    sb.Append(string.Format(@"{0}<br />",
       schedules.Working));
}

lblMsgO.Text = sb.ToString();

sb.Clear();
reader.Close();
con.Close();

另外,对于连接,您应该使用using块来创建和处置连接,而不要自己关闭。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM