循环时检索SQL语句不会进入

时间:2013-12-27 01:15:56

标签: sql database while-loop

在C#中使用3层检索功能时遇到问题。这是代码:

public DistributionStandardPackingUnits getSPUDetail(string distributionID)
{
    DistributionStandardPackingUnits SPUFound = new DistributionStandardPackingUnits();
    using (var connection = new SqlConnection(FoodBankDB.connectionString))
    {
        SqlCommand command = new SqlCommand("SELECT name, description, quantity FROM dbo.DistributionStandardPackingUnits WHERE distribution = '" + distributionID + "'", connection);
        connection.Open();
        using (var dr = command.ExecuteReader())
        {
            while (dr.Read())
            {
                string name = dr["name"].ToString();
                string description = dr["description"].ToString();
                string quantity = dr["quantity"].ToString();

                SPUFound = new DistributionStandardPackingUnits(name, description, quantity);
            }
        }
    }
    return SPUFound;
}

当我在浏览器中运行时,它不会显示任何检索到的数据。当我在调试模式下运行时,我意识到当它到达while循环时,而不是执行dr.Read(),它只是跳过整个while循环并返回null值。我想知道是什么问题造成的。我使用测试查询测试了我的查询,它返回了我想要的东西所以我认为问题不在于Sql语句。

提前致谢。

编辑部分

public static SqlDataReader executeReader(string query)
    {
        SqlDataReader result = null;

        System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);

        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        result = command.ExecuteReader();
        connection.Close();

        return result;
    }

0 个答案:

没有答案