Asp.net添加到数据库

时间:2012-01-10 09:51:32

标签: asp.net sql-server-2008

是否可以从单个文本框添加到数据库中的不同表。

我有一个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);

2 个答案:

答案 0 :(得分:2)

可能是的,但请考虑我的观点:

  1. 考虑一下普通表格,应该可以设计数据库,这样你只需要在一个地方改变它。如果您必须在多个地方更改名称,则可能无法遵循正常形式,并且可以重新设计数据库。
  2. 不建议你进行更新的方式,看看SQLInjection攻击,因为上面的代码很容易受到攻击。使用SQLCommand中的参数而不是创建大字符串是从安全性和性能点执行此操作的更好方法。
  3. 希望我没有太过消极

    安迪

答案 1 :(得分: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();
}