2016-08-08 11 views
0

非常に新しいプログラミングで、アイテムコードがデータベースに存在しないときに新しいアイテムを追加する方法を考えるのが難しい。 else文を追加するまでスムーズに動作するようです。ここに私のコード:アイテムが利用できないときに新しいデータを追加する

private void btnAdd_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      con.Open(); 
      OleDbCommand command = new OleDbCommand(@"Select * from TblInventory where ItemCode=itemcode"); 
      command.Connection = con; 
      command.Parameters.AddWithValue("@itemcode", txtItem.Text); 

      OleDbDataReader reader = command.ExecuteReader(); 

      if (reader.HasRows == true) 
      { 
       OleDbCommand cmd = new OleDbCommand(@"Update TblInventory set Quantity = Quantity + @Quantity 
WHERE ItemCode = @itemcode"); 
       cmd.Connection = con;     
       cmd.Parameters.AddWithValue("@Quantity",Convert.ToInt32(txtQuantity.Text)); 
       cmd.Parameters.AddWithValue("@itemcode", txtItem.Text); 
       cmd.ExecuteNonQuery(); 
       MessageBox.Show("Data Saved !"); 
      } 
      else 
      { 
       OleDbCommand cmdInsert = new OleDbCommand(@"insert into TblInventory (ItemCode,ProductName,Quantity) 
values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "')"); 
       cmdInsert.Connection = con; 
       cmdInsert.ExecuteNonQuery(); 
       MessageBox.Show("New Data Added"); 
      } 

      con.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error " + ex); 
     } 
    } 
+0

SQLインジェクションの警告 –

+1

:THIS TO

OleDbCommand command = new OleDbCommand(@"Select * from TblInventory where ItemCode=itemcode"); 

:THIS FROM ?エラーが発生していますか?挿入クエリ文字列がどのように見えるか確認しましたか?データ用に使用しているテキストボックスには一重引用符はありますか? – PhillipXT

+0

私はあなたの 'Select * from TblInventory 'のItemCode = itemcode'を' itemcode'ではなく '@ itemcode'で見つけました。 –

答えて

1

データベースの既存のレコードを見つけるための最良の方法は、与えられたレコード基準の数を数えることです。

OleDbCommand command = new OleDbCommand(@"Select COUNT(ItemCode) from 
              TblInventory where ItemCode= @itemcode"); 

その後、あなたitemCodeのカウントであるクエリ結果の最初の行の最初の列を返しますExecuteScalar()代わりExecuteReader()

Int32 count = (int32) command.ExecuteScalar(); 

ExecuteScalar()を使用しています。詳細はlinkをご覧ください。

次に、単純な条件付きロジックを実行できます。

if (count > 0) // means that itemCode has 1 or more record count found in the db. 
{ 
    // Do the update logic here.. 
} 
else 
{ 
    // Do the insert logic here... 
} 
0

すでに回答が見つかりました。あなたはそれを実行したときに何が起こる

OleDbCommand command = new OleDbCommand(@"Select * from TblInventory where ItemCode='" + txtItem.Text + "'"); 
+0

これは悪いです、あなたはSQLでエラーが発生する傾向があります注入。あなたのような文字を入力した場合、あなたのクエリはクラッシュします。 'ItemCode = itemcode'節でパラメータを定義するのを忘れてしまったので、代わりに' ItemCode = @ itemcode'と書く必要がありますので、コード行 'command.Parameters.AddWithValue(" @ itemcode "、txtItem.Text);'は '@ itemcode'に特定の値を割り当てます。これはあなたの問題をより効果的に解決します。 –

関連する問題