2012-01-12 34 views
0

我怎麼能只讀一條記錄,當我想要所有記錄它的罰款,但是當我需要@id的特定記錄,我的while循環jums出?如何使用ado.net reader?

[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"); 
    } 
+0

什麼是你的問題? – 2012-01-12 18:24:16

+0

你的代碼看起來不錯,確保你的查詢實際上返回任何行。 – 2012-01-12 18:26:43

+0

@D Stanley,我如何只讀一條記錄,當我希望所有記錄都很好時,但是當我需要@id的特定記錄時,我的while循環出現了? – 2012-01-12 18:26:48

回答

3

while (reader.Read()) { }將在沒有更多記錄要讀取時中斷。由於您的第一條命令刪除了由id標識的記錄,因此使用該標識永遠不會讀取任何內容。

3

如果第二個查詢在第一個查詢中刪除該行,那麼第二個查詢是否會返回任何結果?

+0

謝謝你們,我想我在這一個sholud切換動作:-) – 2012-01-12 18:30:52

+0

有時我們會過度解決問題並錯過顯而易見的錯誤 - 我們都在那裏:) – 2012-01-12 21:24:57

1

您正在使用SqlDataReader。它應該跳過while循環的唯一原因是如果你沒有取回任何記錄。

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(); 
    } 
}