2013-10-22 2 views
2

다음 코드를 가지고 있으며 데이터베이스를 업데이트하지 않습니다. 이 코드는 어떻게 처리하는지 알고 있지만 ExecuteNonQuery()를 호출하면 데이터베이스에 아무 것도 저장하지 않습니다. 작동중인 select 쿼리와 동일하므로 연결 문자열에는 문제가 없습니다. 하지 매개 변수 @key을 -C# ExecuteNonQuery가 데이터베이스를 업데이트하지 않습니다.

const string str = @"Data Source=localhost;Initial Catalog=Items;Integrated Security=True"; 
     static void Main(string[] args) 
     { 
      const string connectionString = str; 

      DataTable DataTableAllWithoutID = new DataTable(); 
#if !test 
      string queryString = "select * from table_items_shelves;"; 
      SqlDataAdapter adapterAllWithoutID = new SqlDataAdapter(queryString, connectionString); 
      adapterAllWithoutID.Fill(DataTableAllWithoutID); 
      adapterAllWithoutID.Dispose(); 
      SqlConnection connection = new SqlConnection(connectionString); 
      connection.Open(); 
      string insertString = "Update table_items_shelves Set Item_ID = @Item_ID where Item_Name = '@key';"; 
      SqlCommand insertCommand = new SqlCommand(insertString, connection); 
      insertCommand.Parameters.Add("@Item_ID", SqlDbType.Int); 
      insertCommand.Parameters.Add("@key", SqlDbType.NVarChar); 
#else 
      DataTableAllWithoutID.Columns.Add("Item_Name", typeof(string)); 
      DataTableAllWithoutID.Columns.Add("Item_ID", typeof(object)); 
      foreach (List<object> row in input) 
      { 
       DataRow newRow = DataTableAllWithoutID.Rows.Add(); 
       newRow.ItemArray = row.ToArray(); 
      } 

#endif 
      //this code will get empty items 
      List<DataRow> nullOrEmpty = DataTableAllWithoutID.AsEnumerable() 
       .Where(x => x.Field<object>("Item_ID") == null) 
       .ToList(); 
      //this creates a dictionary of valid items 
      Dictionary<int, List<DataRow>> dict = DataTableAllWithoutID.AsEnumerable() 
       .Where(x => x.Field<object>("Item_ID") != null) 
       .GroupBy(x => x.Field<object>("Item_ID"), x => x) 
       .ToDictionary(x => Convert.ToInt32(x.Key), x => (List<DataRow>)x.ToList()); 
      //create IEnumerator for the null items 
      IEnumerator<DataRow> emptyRows = nullOrEmpty.GetEnumerator(); 
      Boolean noMoreEmptyRows = false; 
      if (emptyRows != null) 
      { 
       foreach (int key in dict.Keys) 
       { 
        Console.WriteLine(key.ToString()); 
        //get count of items    
        int count = dict[key].Count; 
        int itemID = (int)key; 
        for (int index = count; count < 8; count++) 
        { 
         if (emptyRows.MoveNext()) 
         { 
          //get an item from the null list     
          emptyRows.Current["Item_ID"] = itemID; 
          insertCommand.Parameters["@Item_ID"].Value = itemID; 
          insertCommand.Parameters["@key"].Value = emptyRows.Current["Item_Name"]; 
          insertCommand.ExecuteNonQuery(); 
          Console.WriteLine("current item ID " + itemID); 
          Console.WriteLine("current count " + count); 
          //Console.ReadKey(); 
         }//end if 
         else 
         { 
          noMoreEmptyRows = true; 
          break; 
         }//end else 
        }//end for 
        if (noMoreEmptyRows) 
         break; 
       }//end foreach 
       if (!noMoreEmptyRows) 
       { 
        //increment key to one greater than max value 
        int maxKey = dict.Keys.Max() + 1; 
        int count = 0; 
        while (emptyRows.MoveNext()) 
        { 
         //get an item from the null list     
         emptyRows.Current["Item_ID"] = maxKey.ToString(); 
         insertCommand.Parameters["@Item_ID"].Value = maxKey.ToString(); 
         insertCommand.Parameters["@key"].Value = emptyRows.Current["Item_ID"]; 

          insertCommand.ExecuteNonQuery(); 

          count++; 
         if (count == 8) 
         { 
          maxKey++; 
          count = 0; 
         } 
        } 
       } 
      }//end if 
#if test 
      foreach (DataRow row in DataTableAllWithoutID.Rows) 
      { 
       Console.WriteLine("Item_Name : {0} Item ID : {1}", 
        row["Item_Name"], row["Item_ID"]); 
      } 
#endif 

      FIllGroupID(str); 
      Console.ReadKey(); 

     } 
+0

정말'UPDATE' 일 때'InsertString'이라고 불리는 이유는 무엇입니까 ?? !! –

+0

@marc_s가 업데이트되기 전에 삽입 중입니다. 나는 그것을 바꿔야 해. – mubi

+0

그래, 나는 분명히 그것을 바꿀 것이다 - 언제나 * 최소한의 서프라이즈 * 원리를 생각해 보라 - ** 그것이 ** Insert .....라고 불리우면 ** Insert **와 관련이있다. '전혀 다른 게 아니야 .... –

답변

8
where Item_Name = '@key'; 

이 는 문자 '@key'에 일치합니다. 당신은 아마도 원할 것입니다 :

where Item_Name = @key; 
+0

감사합니다. 운이 좋다면이 투표에서 부정적인 표를 얻지 못했습니다. – mubi

+0

@ mubi meh; 그것은 아마도 하나의 시나리오에 특정 적이지 만, 최소한 당신은 그것에 관련된 모든 관련 정보를 포함 시켰습니다. –

관련 문제