将Asp.net添加到数据库

问题描述:

是否可以从单个文本框添加到数据库中的不同表中。将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

这是可能肯定的,但考虑我点以下:

  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

如果你使用一个交易(你应该使用参数,以获得周围的一些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(); 
}