2011-09-02 82 views
6

多個表我想知道是什麼做的標準/最好的方法如下:將數據插入到網絡形式

我在asp.net形式的Web應用程序,並使用C#

用戶將輸入數據到表單中,然後單擊INSERT,它會將數據插入到4個不同的表中。

的字段有:

primarykey, animal, street, country 

形式允許多個動物,多條街道和每PrimaryKey的多個國家。所以當我有數據是這樣的:

[1],[rhino,cat,dog],[luigi st, paul st], [russia,israel] 

我需要它插入到表是這樣的:

table1: 
1,rhino 
1,cat 
1,dog 

table2: 
1,luigi st 
1, paul st 

table3: 
1,russia 
1,israel 

問題

  1. 我就如何徹底報廢去做這個。如果我只有一個表和一組數據每個主鍵我只是使用InsertQuery並以這種方式執行,但由於它是多個表,我不知道該怎麼做?

  2. 我應該使用什麼控件才能讓用戶輸入多個值?目前我只是使用文本框,並想用分號分隔條目,但這可能不是正確的方法。

+0

對於(1):您可以使用交易。看到這個答案︰http://stackoverflow.com/questions/2044467/how-to-update-two-tables-in-one-statement-in-sql-server-2005/2044520#2044520 –

回答

3

我想建議你利用新的多行INSERT語句在2008年使SQL,你可以只通過一個sql語句是這樣的:

INSERT INTO table1(id,animal_name) values (1,cat),(1,dog),(1,horse)... 

要你的SqlCommand但我不」不知道如何構建一個像沒有SQL注入攻擊的受害者那樣的陳述。

另一種方法是在你的SQL數據庫定義數據表類型: enter image description here

enter image description here

,然後構造在C#的DataTable,你的數據表類型定義相匹配:

DataTable t = new DataTable(); 
t.Columns.Add("id"); 
t.Columns.Add("animal_name"); 
foreach(var element in your animals_list) 
{ 
    DaraRow r = t.NewRow(); 
    r.ItemArray = new object[] { element.id, element.animal_name }; 
    t.Rows.Add(r); 
} 

// Assumes connection is an open SqlConnection. 
using (connection) 
{ 
    // Define the INSERT-SELECT statement. 
    string sqlInsert = "INSERT INTO dbo.table1 (id, animal_name) SELECT nc.id, nc.animal_name FROM @animals AS nc;" 

    // Configure the command and parameter. 
    SqlCommand insertCommand = new SqlCommand(sqlInsert, connection); 
    SqlParameter tvpParam = insertCommand.Parameters.AddWithValue("@animals", t); 
    tvpParam.SqlDbType = SqlDbType.Structured; 
    tvpParam.TypeName = "dbo.AnimalTable"; 

    // Execute the command. 
    insertCommand.ExecuteNonQuery(); 
} 

Read more here

或者如果您熟悉存儲過程,則與之前的建議相同,但存儲過程將接收DataTable t作爲參數。

如果以上都不適合您,請從Connection對象創建一個SqlTranscation,並遍歷每個數據集的每一行,以在相應的表中插入記錄並最終提交事務。 Example here.

+0

非常感謝,我會在哪裏我會放置代碼?在INSERTING活動中? –

2

使用前端的複選框。有一個服務/存儲庫來保存用戶數據。類似如下:

public void UpdateUserAnimals(Guid userId, string[] animals) 
{ 
    using (SqlConnection conn = new SqlConnection("connectionstring...")) 
    { 
     using (SqlCommand cmd = new SqlCommand("Insert Into UserAnimals(UserId, Animals) values (@UserId, @Animal)")) 
     { 
      conn.Open(); 
      cmd.Parameters.AddWithValue("@UserId", userId); 
      foreach(string animal in animals) 
      { 
       cmd.Parameters.AddWithValue("@Animal", animal); 
       cmd.ExecuteNonQuery(); 
      } 
     } 
    } 
} 

有更復雜的解決方案,但這是一個簡單的解決方案。

+0

美麗的答案我會嘗試 –