asp.net SQL Server插入语句tidyup +错误

Ink*_*key 0 c# asp.net

我有一个将数据插入数据库的表单.

某些领域并不总是需要.当我在代码中留下这些空白时,我得到一个错误说.

列名或提供的值数与表定义不匹配.

这就是我如何设置数据库.SQL Server 2008

[youthclubid]
[youthclubname]
[description]
[address1]
[address2]
[county]
[postcode]
[email]
[phone]
Run Code Online (Sandbox Code Playgroud)

这是我连接到数据库并执行插入的代码.

connection.Open();
cmd = new SqlCommand("insert into youthclublist values ('" + youthclubname.Text + "', '" + description.Text + "','" + address1.Text + "','" + address2.Text + "', '" + county.Text + "', '" + postcode.Text + "', '" + email.Text + "', '" + phone.Text + "')", connection);
cmd.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 5

你有两个主要问题:

1)将SQL语句连接在一起容易发生SQL注入攻击 - 不要这样做,而是使用参数化查询

2)您没有定义要在表格中插入哪些列 - 默认情况下,这些列都是列,如果您没有为所有列提供值,您将看到您看到的错误.

我的建议:始终使用参数化查询并在INSERT语句中明确定义列.这样,您可以定义哪些参数具有值,哪些不具有值,并且您可以安全地免受注入攻击 - 并且您的性能也会更好!

string insertStmt = 
       "INSERT INTO dbo.YouthClubList(Youthclubname, [Description], " +
         "address1, address2, county, postcode, email, phone) " +
       "VALUES(@Youthclubname, @Description, " +
         "@address1, @address2, @county, @postcode, @email, @phone)";

using(SqlConnection connection = new SqlConnection(.....))
using(SqlCommand cmdInsert = new SqlCommand(insertStmt, connection))
{
   // set up parameters
   cmdInsert.Parameters.Add("@YouthClubName", SqlDbType.VarChar, 100);
   cmdInsert.Parameters.Add("@Description", SqlDbType.VarChar, 100);
   .... and so on

   // set values - set those parameters that you want to insert, leave others empty
   cmdInsert.Parameters["@YouthClubName"].Value = .......;

   connection.Open();
   cmdInsert.ExecuteNonQuery();
   connection.Close();
}
Run Code Online (Sandbox Code Playgroud)