2017-04-21 48 views
-5

我的代码的一部分受到SQL注入。下面是代码如何克服SQL注入

public int Insert(string usrtest) 

    { 
DataTable dt = new DataTable(); 
      SqlConnection con = new SqlConnection(conn); 
      // SqlCommand cmd = new SqlCommand("select * from table where [email protected]", con); 
      SqlDataAdapter adp = new SqlDataAdapter("select * from table where [email protected]", con); 
      con.Open(); 
      adp.SelectCommand.Parameters.AddWithValue("@name", usrtest); 

      adp.Fill(dt); 
      SqlCommand cmd1 = new SqlCommand("Update table set Date='" + DateTime.Now + "' where name='" + usrtest + "'", con); 

      cmd1.ExecuteNonQuery(); 
      con.Close(); 
} 
+0

难道你没有看到两段代码之间的区别吗?首先正确使用参数化查询,然后再绕过所有内容并再次通过字符串连接手工制作SQL。在你的第二个查询中也使用参数,你就完成了。 – CodeCaster

+0

您还应该为SqlConnection,SqlCommand和SqlDataAdapter使用“using”语句,请参阅https://www.dotnetperls.com/sqlconnection和http://stackoverflow.com/questions/18205560/do-need-对明确,处置-的SqlDataAdapter。 – Polyfun

+0

我有一个gridview的itemtemplate文本框控件,可以编辑。这是代码 这是否构成一个跨站点脚本风险? – Aswini

回答

0

的问题是在下面的命令,在您使用字符串连接:

SqlCommand cmd1 = new SqlCommand("Update Usrtable set password_change_status=1, Date='" + DateTime.Now + "' where Uname='" + txtusr + "'", con); 

因为你已经与前一个,在您使用Parameters完成上面的命令应该被踩踏。

var cmd1 = new SqlCommand("Update Usrtable set password_change_status=1, [email protected] where [email protected]", con); 
cmd1.Parameters.AddWithValue("@Date",DateTime.Now); 
cmd1.Parameters.AddWithValue("@Uname",txtusr); 
2

您似乎已经知道如何使用绑定参数,就像您在代码中执行了前4行一样。把它们用于你的第二个陈述。