c# - 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 查询时出现两行。
解决方案
在您的循环中,您每次都会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
块来创建和处理连接,而不是自己关闭它。
推荐阅读
- python - 如果迭代器不以 1 为增量增加,则拆分升序整数列表的有效方法
- kubernetes - 如何创建重定向网址
- python - 用漂亮的汤解析和排序 html 标签
- excel - 从 Excel VBA 中此文件夹路径内的文件中获取文件夹路径
- python - 如何使用 Pytest 测试错误消息
- python - 使用 Dask 防止多次读取数据
- python - 使用递归打印帕斯卡三角形的第 n 行
- react-native - Expo 构建失败,请求失败,状态码为 400
- magento2 - 将数据库复制到新表后我们面临一些问题,升级命令无法显示这些类型的错误
- ios - 如何在 WKWebView 中拦截 XHR 请求?