2016-08-17 8 views
1

私は、ワンクリックで複数のアイテムを追加できる在庫システムを作成しています。どうすればいい?私はすでにデータを保存することができますが、ただ一つのテキストボックスです。データベースの1列に複数のテキストボックスを追加する

//Add new Data if Item Code is not exit; 
      { 
       OleDbCommand cmdInsert = new OleDbCommand(@"insert into TblInventory (ItemCode,ProductName,Quantity,DateAndTime) values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "','" + time + "')"); 
       cmdInsert.Connection = con; 

       cmdInsert.ExecuteNonQuery(); 
       MessageBox.Show("You added New " + txtQuantity.Text + " " + txtProduct.Text + " in the list", "New Item"); 
      } 
      con.Close(); 

IはtxtItem2txtProduct2txtQuantity2である別のテキストボックスを持っていると仮定します。 insert into statementにはどこにあるのですか?以下のような代わりに、文字列の連結の

+1

さらに別のSQLインジェクション:パラメータについては、最初にお読みください:https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbparameter –

+0

それから質問に詳しい説明をしてください:P – ThatAwesomeCoder

+0

@ThatAwesomeCoder先ほどご紹介してください質問 –

答えて

1

まず、使用パラメータ、:

OleDbCommand cmdInsert = new OleDbCommand(
    @"insert into TblInventory (ItemCode,ProductName,Quantity,DateAndTime) values (@ItemCode,@ProductName,@Quantity,@DateAndTime)"); 
cmdInsert.Parameters.AddWithValue("ItemCode", txtItem.Text); 
cmdInsert.Parameters.AddWithValue("ProductName", txtProduct.Text); 
cmdInsert.Parameters.AddWithValue("Quantity", txtQuantity.Text); 
cmdInsert.Parameters.AddWithValue("DateAndTime", time); 

第二に、あなたは多くの挿入、使用ループが必要な場合。または、4つのパラメータItemCode,ProductName,Quantity,DateAndTimeを使用して挿入コードをラップします。 txtSomething.Text値への直接参照するのではなく、それらを使用して、すなわち(擬似コード):あなたは以下のように書くことができForループ

InsertRecord(txtItem.Text, txtProduct.Text, ...); 
InsertRecord(txtItem2.Text, txtProduduct2.Text, ...); 

var rows = new[] 
{ 
    new {Item = "item1" /*value from txtItem1*/, Product = "product1", Quantity = "Quantity1" /*should be int?*/}, 
    new {Item = "item2" /*value from txtItem2*/, Product = "product2", Quantity = "Quantity2"} 
}; 

foreach (var row in rows) 
{ 
    OleDbCommand cmdInsert = new OleDbCommand(
     @"insert into TblInventory (ItemCode,ProductName,Quantity,DateAndTime) values (@ItemCode,@ProductName,@Quantity,@DateAndTime)"); 
    cmdInsert.Parameters.AddWithValue("ItemCode", row.Item); 
    cmdInsert.Parameters.AddWithValue("ProductName", row.Product); 
    cmdInsert.Parameters.AddWithValue("Quantity", row.Quantity); 
    cmdInsert.Parameters.AddWithValue("DateAndTime", DateTime.Now); 
    cmdInsert.Connection = conn; 
    cmdInsert.ExecuteNonQuery(); 
} 
+0

あなたはそれのためのサンプルループを作成するのを助けてもらえますか?私のアイテムに5つの重複があると仮定します。どうすればいい? –

+0

また、複数のトランザクションをデータベースに作成したくない場合もあります。一括挿入の方法を検索します。 – Doruk

+0

ありがとうございました。@パベル。量については、それはint sirとして宣言する必要があります。 –

0

あなたが入力パラメータとしてXMLを受け入れるストアドプロシージャを作成することができ、かつストアドプロシージャでypuはxmlを解析してテーブルにデータを挿入します

関連する問題