IDataReader没有读,没有错误

时间:2012-11-07 22:55:57

标签: c# asp.net sqldatareader idatareader

我意识到IDataReader已经过时,有些人将其视为脏代码,但在我正在研究的网站上,这就是他们使用的内容。我有一个IDataReader语句来运行查询以使用多个连接从表中获取特定的id。现在这个站点有一个DAL,但它只支持一次从一个表中进行选择,因此使用带有连接的select语句不能使用它。这就是我被迫使用IDataReader的原因。

 if (Request.QueryString["CategoryId"].ToString() == "0")
                {
                    using (IDataReader getCategoryID = DB.GetRS("SELECT ItemCatalogCategory.CategoryID FROM UserCustomerCatalog INNER JOIN ItemCatalogCategory ON UserCustomerCatalog.ItemProfileCatalogID = ItemCatalogCategory.ItemProfileCatalogID " +
                              "INNER JOIN ItemCategory ON ItemCatalogCategory.CategoryID = ItemCategory.CategoryID INNER JOIN StoreCatalog ON UserCustomerCatalog.StoreCatalogID = StoreCatalog.StoreCatalogID " +
                              "WHERE UserCustomerCatalog.ItemProfileCatalogID = '" + Request.QueryString["CatalogID"] + "' AND UserCustomerCatalog.CustomerID =' " + Session["Customer"].ToString() + "' AND ItemCategory.ProductID = '" + productis + "'"))
                    {

                        if (getCategoryID.Read())
                        {
                            string categoryID = getCategoryID["ItemCatalogCategory.CategoryID"].ToString();

                            string lookmike = Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + categoryID;
                            Response.Redirect(Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + categoryID);

                        }
                        else
                        {
                            Response.Redirect(Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + Request.QueryString["CategoryId"]);
                        }

                    }//end using getCategoryID
                }

这就是我所拥有的,但是当它到达时:

if (getCategoryID.Read())

它呈现为false,没有抛出异常,也没有错误或警告。我在过去做过这种类型的选择没有问题,但我无法弄清楚为什么.Read()返回false。

有人可以提出不读的可能原因吗?如果需要更多代码,我可以根据需要提供。如有任何帮助,请提前感谢。

1 个答案:

答案 0 :(得分:1)

查看您的SQL文本,可能会对结果造成严重错误

 "WHERE UserCustomerCatalog.ItemProfileCatalogID = '" + Request.QueryString["CatalogID"] + 
 "' AND UserCustomerCatalog.CustomerID =' " + Session["Customer"].ToString() + "' AND ..... "
                                    here ^

该空间会破坏您的查询并且不会产生任何结果。

我还要重申,你有SQL Injection的问题正如其他成员已经说过的那样。您可以为实际的GetRS实现添加一个重载,它还接收一个SQLParameter集合,以添加到用于构建SqlDataReader的命令中。像这样的东西

public SqlDataReader GetRS(string sqlText, SqlParameter[] prm)
{
      ....
      SqlCommand cmd = new SqlCommand(sqlText, conn);
      cmd.Parameters.AddRange(prm);
      .....
}

然后开始更新调用代码。