如何使用ado.net阅读器?

时间:2012-01-12 18:22:42

标签: c# .net sql asp.net-mvc-3 ado.net

我怎么能只读一条记录,当我希望所有记录都很好但是当我需要一个带有@id的特定记录时,我的while循环会出错?

[HttpGet]
public ActionResult DeleteArticle(int ProductID)
{
    int id = ProductID;

    if (ModelState.IsValid)
    {
           string connStr = ConfigurationManager.ConnectionStrings["AdminServices"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(connStr))
            {
                connection.Open();

               //delete from database
                using (SqlCommand command = new SqlCommand("DELETE FROM MyTable  WHERE id = @id", connection))
                {
                    command.Parameters.AddWithValue("@id", id);
                    command.ExecuteNonQuery();
                }

                 //read imagePathe from Database from database
                using (SqlCommand command = new SqlCommand("SELECT * FROM MyTable WHERE id = @id", connection))
                {

                    command.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = id;
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read()) // --> here it skips while loop ????
                    {

                        string ImagePath = (string)reader["DbImagePath"];

                    }

                }

            }
        }
        return RedirectToAction("Index", "Admin");
    }

4 个答案:

答案 0 :(得分:3)

第二个查询假设如果你用第一个删除行会返回任何内容?

答案 1 :(得分:3)

当没有更多记录要阅读时,

while (reader.Read()) { }将会中断。由于您的第一个命令删除了id标识的记录,因此永远不会有任何内容与该ID一起阅读。

答案 2 :(得分:1)

您正在使用SqlDataReader。它应该跳过while循环的唯一原因是你没有找回任何记录。

答案 3 :(得分:1)

以下是样本

private static void ReadOrderData(string connectionString)
{
    string queryString =
        "SELECT OrderID, CustomerID FROM dbo.Orders;";

    using (SqlConnection connection =
               new SqlConnection(connectionString))
    {
        SqlCommand command =
            new SqlCommand(queryString, connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        // Call Read before accessing data.
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
        }

        // Call Close when done reading.
        reader.Close();
    }
}