如何克服SQL注入[重复]

时间:2022-09-06 22:17:27

This question already has an answer here:

这个问题在这里已有答案:

A part of my code is subjected to SQL injection. Below is the code

我的代码的一部分受到SQL注入。以下是代码

public int Insert(string usrtest )

    {
DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection(conn);
            // SqlCommand cmd = new SqlCommand("select * from table where name=@name", con);
            SqlDataAdapter adp = new SqlDataAdapter("select * from table where name=@name", 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();
}

2 个解决方案

#1


0  

The problem is in the following command, where you use string concatenation:

问题出在以下命令中,您使用字符串连接:

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

The above command should be treaded as you have already done with the previous one, where you use Parameters.

上面的命令应该像你在上一个命令中那样使用参数。

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

#2


2  

You seem to already know how to use bind parameters, as you did just 4 lines before in your code. Use them for your second statement as well.

您似乎已经知道如何使用绑定参数,因为您在代码中只执行了4行。也可以将它们用于第二个陈述。

#1


0  

The problem is in the following command, where you use string concatenation:

问题出在以下命令中,您使用字符串连接:

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

The above command should be treaded as you have already done with the previous one, where you use Parameters.

上面的命令应该像你在上一个命令中那样使用参数。

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

#2


2  

You seem to already know how to use bind parameters, as you did just 4 lines before in your code. Use them for your second statement as well.

您似乎已经知道如何使用绑定参数,因为您在代码中只执行了4行。也可以将它们用于第二个陈述。