为什么SQL语句不起作用?

时间:2016-04-08 02:43:00

标签: c#

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

我按照我研究过的示例使用了params但是我得到了这个错误:“当前上下文中的名称描述”在以下代码行中:“sqlCommand.Parameters.AddWithValue(”@ Description“,newDescription.Description) ;” 我怎样才能解决这个问题?

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

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

2 个答案:

答案 0 :(得分:1)

namespace Product
{
    class Program
    {
        static void Main(string[] args)
        {
             SqlConnection conn = new SqlConnection(
                 "Data Source=localhost\\Win;Initial Catalog=Databasee; Integrated Security=True");

             string sql =
                 "INSERT INTO Products " +
                 "(Description)" +
                 "Values (@Description)";

             string toxin = "''); DELETE FROM Products; --";

             SqlCommand sqlCommand = new SqlCommand(sql, conn);
             sqlCommand.Parameters.AddWithValue("@Description", toxin);
             conn.Open();
             sqlCommand.ExecuteNonQuery();
             conn.Close();
        }

     }
 }

答案 1 :(得分:0)

首先是你的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();