2012-01-12 1 views
0

どのように私はすべてのレコードが罰金だが、私は@ idと、特定のレコードが必要なときに、私のwhileループjumsアウト1つのレコードを読み取ることができますか?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

あなたの質問は何ですか? –

+0

コードが正常に表示されていることを確認してください。 –

+0

@D Stanley、どのようにすべてのレコードがうまくいきたいのですが、@ idで特定のレコードが必要なときに、1つのレコードしか読み込めません。 –

答えて

3

while (reader.Read()) { }が解除されます。あなたの最初のコマンドはidで示されるレコードを削除するので、そのIDで読み取るものは決してありません。ここで

3

2番目のクエリは、最初のクエリで行を削除すると何かを返すとしますか?

+0

ありがとうございます、私はこの1つのアクションを切り替えます:-) –

+0

時々、私たちは問題を克服して明白なエラーを見逃しています。 –

1

あなたは正しくSqlDataReaderを使用しています。あなたがレコードを返さない場合は、ループの間にそれをスキップしなければならない唯一の理由です。読むためにこれ以上のレコードがあるとき

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