0

我正在使用数据阅读器将特定列数据显示到网格视图中。实际上我想从表中获取最后一天的记录。

 DateTime yestarday = DateTime.Today.AddDays(-1);
            string query = "select NAME,CLOSING_READING,RATE  from CASHSALE_DETAIL where DATE = '" + yestarday + "'";
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Conn;
            cmd.CommandText = query;
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                CashSaleVoucherGridView.Rows.Add(num, "", dr["NAME"].ToString(), dr["CLOSING_READING"].ToString(), "", "", "", dr["RATE"].ToString());
                num++;
            }

在上面给定的查询数据阅读器返回我 0 记录。有什么建议吗???

4

3 回答 3

0

首先检查您的选择是否查询它的返回记录,然后添加 dr.HasRows 以检查您的数据阅读器是否返回行

DateTime yesterday = DateTime.Today.AddDays(-1);
string query = "select NAME,CLOSING_READING,RATE  from CASHSALE_DETAIL where DATE = @date";
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@date", yesterday );
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
     while (dr.Read())
            {
                CashSaleVoucherGridView.Rows.Add(num, "", dr["NAME"].ToString(), dr["CLOSING_READING"].ToString(), "", "", "", dr["RATE"].ToString());
                num++;
            }
}
else
{
//Throw error ("No rows found.");
}

此致

于 2012-12-27T09:42:28.137 回答
0

问题在于这个声明

string query = "select NAME,CLOSING_READING,RATE  from CASHSALE_DETAIL where DATE = '" + yestarday + "'";

使用参数化命令

DateTime yesterday = DateTime.Today.AddDays(-1);

string query = "select NAME,CLOSING_READING,RATE  from CASHSALE_DETAIL where DATEADD(dd, 0, DATEDIFF(dd, 0, DATE )) = DATEADD(dd, 0, DATEDIFF(dd, 0, @yesterday))";


SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@yesterday", yesterday);
SqlDataReader dr = cmd.ExecuteReader();
于 2012-12-27T09:37:14.720 回答
0

您可以像这样格式化日期字段

string query = "select NAME,CLOSING_READING,RATE  from CASHSALE_DETAIL
where convert(varchar(15),DATE,101)= '" + yestarday + "'";

但是@BizApps 和@mdcuesta 提到的方法如下所示的错误非常少

cmd.Parameters.AddWithValue("@yesterday", yesterday);
于 2012-12-27T10:47:22.290 回答