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

C# asp.net SQL Server插入语句tidyup+;错误,c#,asp.net,C#,Asp.net,我有一个表单,可以将数据插入数据库 有些字段并不总是需要的。 当我在我的代码中保留这些空白时,我会得到一个错误,即 提供的值的列名或数目与表不匹配 定义 这就是我设置数据库的方式。SQL Server 2008 [youthclubid] [youthclubname] [description] [address1] [address2] [county] [postcode] [email] [phone] 下面是我连接到数据库并执行插入的代码 connection.Open(); cmd

我有一个表单,可以将数据插入数据库

有些字段并不总是需要的。 当我在我的代码中保留这些空白时,我会得到一个错误,即

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

这就是我设置数据库的方式。SQL Server 2008

[youthclubid]
[youthclubname]
[description]
[address1]
[address2]
[county]
[postcode]
[email]
[phone]
下面是我连接到数据库并执行插入的代码

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();

这不是为此类语句使用SqlParameter的代码

你的代码是这样的

  SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwind_ConnectionString"].ConnectionString);

        //Create Command object
        SqlCommand nonqueryCommand = thisConnection.CreateCommand();

        try
        {

            // Create INSERT statement with named parameters
            nonqueryCommand.CommandText = "INSERT  INTO Employees (FirstName, LastName) VALUES (@FirstName, @LastName)";

            // Add Parameters to Command Parameters collection
            nonqueryCommand.Parameters.Add("@FirstName", SqlDbType.VarChar, 10);
            nonqueryCommand.Parameters.Add("@LastName", SqlDbType.VarChar, 20);


            nonqueryCommand.Parameters["@FirstName"].Value = txtFirstName.Text;
            nonqueryCommand.Parameters["@LastName"].Value = txtLastName.Text;

            // Open Connection
            thisConnection.Open();

            nonqueryCommand.ExecuteNonQuery();
        }

        catch (SqlException ex)
        {
            // Display error
            lblErrMsg.Text = ex.ToString();
            lblErrMsg.Visible = true;
        }

        finally
        {
            // Close Connection
            thisConnection.Close();

        }

您需要告诉SQL server要插入的字段

        insert into youthclublist(youthclubid, youthclubname, ....) values ('" + youthclubname.Text + "', '" + description.Text + "'.....

你很好。

你有两个主要问题:

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();
}

第一个主要问题是在查询中连接输入。这使您的应用程序极易受到攻击。不要这样做。使用一个

insert语句的常规语法如下所示:

Insert into <TableName> (Col1, Col2...Coln) values (val1, val2...valn)
插入(Col1,Col2…Coln)值(val1,val2…valn)
如果只需要插入一组选定的列,则需要在列列表中提供要插入数据的列的列表

如果未指定列列表,则表示正在向每个列插入数据

因此,您可以检查输入,如果不存在,则可以省略相应的列


另一个更好的方法是使用存储过程。这将缓解这个问题。

虽然在编程中是个新手,但我知道插入数据库的最简单方法是创建一个“save”存储过程,然后通过连接字符串调用它。相信我,这是最好的方法。

另一种方法是使用LINQ to SQL。我发现这要容易得多。遵循以下步骤

  • 将新的LINQ to SQL类添加到项目中。确保文件扩展名为“.dbml”。命名您选择的名称说“YouthClub.dbml”
  • 使用服务器资源管理器将数据库连接到Visual Studio
  • 将您的表拖到或设计器中。(不允许我发布图像)

  • 现在可以使用此代码保存到数据库

        //Create a new DataContext
        YouthClubDataContext db = new YouthClubDataContext(); 
    
        //Create a new Object to be submitted
        YouthClubTable newYouthClubRecord = new YouthClubTable();
    
        newYouthClubRecord.youthlubname = txtyouthclubname.Text;
        newYouthClubRecord.description = txtdescription.Text;
        newYouthClubRecord.address1 = txtaddress1.Text;
        newYouthClubRecord.address2 = txtaddress2.Text;
        newYouthClubRecord.county = txtcounty.Text;
        newYouthClubRecord.email = txtemail.Text;
        newYouthClubRecord.phone = txtphone.Text;
        newYouthClubRecord.postcode = txtpostcode.Text;
    
        //Submit to the Database
        db.YouthClubTables.InsertOnSubmit(newYouthClubRecord);
        db.SubmitChanges();
    

  • 希望这次我给出了一个真实的答案

    您是否已经将您的pk列
    youthclubid
    设置为
    Is Identity=Yes
    ?他正在为他的错误寻求解决方案,您不需要总是使用SQLParameters,这取决于开发人员。@Dipak Goswami-我的系统挂起,无法发布示例…………现在它已更新+1,您不需要显式的
    连接。Close()
    with
    using statement
    @TimSchmelter:你没有,但我还是喜欢,这让我的意图更加清晰,虽然这很有帮助(顺便说一句:
    YouthClubID
    是一个INT-IDENTITY列,不需要在列列表中指定),这并没有以任何方式解决SQL注入的主要问题…@marc_s,他从来没有想要SQL注入的解决方案,他希望我们解决他的具体错误…仅此而已。。。我同意你们所有人的意见,但在这里我的意图是解决问题。我从不想把我所有的知识都扔掉,因为这可能会让提问者感到困惑。事实上,这并不是一个真正的答案。如果您觉得某个过程更好,请提供一个代码示例,说明如何调用该过程以及该过程的外观。