C# 为什么SQL语句不工作?

C# 为什么SQL语句不工作?,c#,C#,我需要使这个insert语句适应SQL注入 根据我研究的示例,我使用了params,但在下面的代码行中出现以下错误:“name Description不存在于当前上下文中:”sqlCommand.Parameters.AddWithValue(“@Description”,newDescription.Description);“ 我怎样才能解决这个问题 我还包括了一个“测试”字符串,以证明它对攻击具有弹性,传递该字符串,然后在SQL Server中检查数据库是否安全。这是最好的测试方法吗 Ed

我需要使这个insert语句适应SQL注入

根据我研究的示例,我使用了params,但在下面的代码行中出现以下错误:“name Description不存在于当前上下文中:”sqlCommand.Parameters.AddWithValue(“@Description”,newDescription.Description);“ 我怎样才能解决这个问题

我还包括了一个“测试”字符串,以证明它对攻击具有弹性,传递该字符串,然后在SQL Server中检查数据库是否安全。这是最好的测试方法吗

Edit: Thanks to @Tibrogargan, who solved this issue. 

首先是您的newDescription。Description未声明,这就是它显示错误的原因

如果您有一个名为Description的类,则以下是实例化该类的方式:

Description newDescription = new Description();
关于如何使用参数进行插入的问题,请看下面的方法

您可以这样做:

string sql = "INSERT INTO Products (Description) Values (@Description)";
                    SqlCommand sqlCommand = new SqlCommand(sql, conn);
                    sqlCommand.Parameters.Add("@Description", SqlDbType.Varchar).Value = newDescription.SomePropertyInsideYourClass;
                    conn.Open();
                    sqlCommand.ExecuteNonQuery();
                    conn.Close();

看起来newDescription没有在任何地方声明。错误是什么?代码正在编译吗?@Tibrogargan是的,你是对的,声明代码的最佳方式是什么?代码在哪里?我应该在SqlConnection连接之前声明它吗?谢谢。这和SQL无关。在您发布的代码的任何地方,都没有名为
newDescription
的内容,因此不能在参数创建代码中使用它。很难告诉你在哪里申报,因为我们不知道它是什么,也不知道它来自哪里。这是你的代码-难道你不知道吗?@KenWhite是的,没错,我对编码还不熟悉,最好的方法是什么?这就是解决方案!非常好用,非常感谢!
string sql = "INSERT INTO Products (Description) Values (@Description)";
                    SqlCommand sqlCommand = new SqlCommand(sql, conn);
                    sqlCommand.Parameters.Add("@Description", SqlDbType.Varchar).Value = newDescription.SomePropertyInsideYourClass;
                    conn.Open();
                    sqlCommand.ExecuteNonQuery();
                    conn.Close();