首页 > 解决方案 > SQL Query 返回 2 个结果,但在 c# 网页中仅显示 1 个结果

问题描述

我有一张名为 Schedule 的营业时间表,其中包含四列:Id、Working、Starting 和 Finishing。

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];

然后我创建了一个名为 Scheduling 的类。

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 查询时出现两行。

标签: c#sqlarraylist

解决方案


在您的循环中,您每次都会default.aspx.cs覆盖该值。lblMsg0您应该退出循环外部的写入label和清除StringBuilder(如果您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块来创建和处理连接,而不是自己关闭它。


推荐阅读