2012-01-10 72 views
0

是否可以從單個文本框添加到數據庫中的不同表中。將Asp.net添加到數據庫

我有一個addclub網絡表格,我想將clubname添加到許多不同的表格。

以下是我目前的代碼。

cmd = new SqlCommand("insert into youthclublist(youthclubname, description, address1, address2, county, postcode, email, phone) values ('" + youthclubname.Text + "', '" + description.Text + "','" + address1.Text + "','" + address2.Text + "', '" + county.Text + "', '" + postcode.Text + "', '" + email.Text + "', '" + phone.Text + "')", connection); 
+3

你有什麼問題?! – 2012-01-10 09:53:22

+0

我假設你的問題是多重插入。是的,你可以插入你的數據從文本框單擊插入多個表,解釋你的問題更清楚.. – Murtaza 2012-01-10 09:53:33

+0

問題是,目前的代碼只是添加到一個表我想知道我將如何改變它,所以它增加到多個表格 – Inkey 2012-01-10 09:57:33

回答

2

這是可能肯定的,但考慮我點以下:

  1. 想想範式,它應該是可以設計的數據庫,所以你只需要改變它在一個地方。如果您必須在多個地方更改名稱,則可能不會遵循正常的格式,並且可能會重新設計數據庫。
  2. 您正在進行更新的方式不可取,請查看SQLInjection攻擊,因爲上述代碼易受此影響。使用SQLCommand中的參數而不是創建大字符串是從安全性和性能角度執行此操作的更好方法。

希望我一直沒太消極

安迪

+0

非常感謝 – Inkey 2012-01-10 10:11:43

+1

+1,非常好的建議。另外,如果您不想(或不能)更改數據庫結構,請考慮使用存儲過程執行多次插入操作。並把它們包裝在一個交易中。這將有助於您的表格之間的一致性。 – Matt 2012-01-10 10:23:56

+0

謝謝你們真的很欣賞我到這裏來的答案 – Inkey 2012-01-10 10:33:36

1

如果你使用一個交易(你應該使用參數,以獲得周圍的一些SQL注入攻擊的問題),像這樣你可以做到這一點(這意味着所有的鑲片在一個單獨的塊進行比做他們一個接一個的)安全數據庫上:

using (var cmd = new SqlCommand("BEGIN TRANSACTION;" 
      + "INSERT INTO youthclublist(youthclubname) VALUES (@youthclubname);" 
// Add all your INSERT statements here for the other tables in a similar way to above (I simplified it to show just one column, but you get the idea) 
      + "COMMIT;", conn)) 
{ 
    // Add your parameters - one for each of your text boxes 
    cmd.Parameters.Add("@youthclubname", SqlDbType.NVarChar).Value = youthclubname.Text; 

    // execute the transaction 
    cmd.ExecuteNonQuery(); 
}