数据读取器不从表中读取数据

时间:2012-12-27 09:34:47

标签: sql-server c#-4.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记录。 任何Suggstions ????

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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.");
}

最好的问候

答案 2 :(得分: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);