Search code examples
sql-injectionprepared-statement

How to correctly insert a parameter into an existing sql query to avoid SQL Injections


I have seen some answers already but my query is a little bit different:

Here is an original query:

cmd.CommandText = "select count(Table1.UserID) from Table1 INNER JOIN 
Table2 ON Table1.ID = Table2.ID where Table1.Userid = " + UserID + " and
Table1.Number != '" + Number +"' and Table2.ID < 4";

Here is a modified query for SQL Injections:

cmd.CommandText = "select count(Table1.UserID) from Table1 INNER JOIN 
Table2 ON Table1.ID = Table2.ID where Table1.Userid = @userId and
Table1.ID != @Number and Table2.ID < 4";

If you can notice, the first query has UserId surrounded by double quotes: ..." + UserID +"... and Number us surrounded by single and double quotes: ...'" + Number + "'...

Here is how I'm setting parameters:

cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Number", Number); 
cmd.Parameters.AddWithValue("@userId",UserID);

where UserID is an integer and Number is a string.

So, my question is, if the modified query formatted the right way? Is there any difference how to put @UserId and @Number parameters into a query considering the different ways they are specified in the original query?


Solution

  • I have been working on .net Mvc for a long time, and I can ensure you the parameters are correctly fixed by yourself in the second case, and you do not need to worry. By the way you can still debug and test if you can inject yourself. Briefly, your code looks great and invulnerable.

    This is how i do it, which is similar and also as safe as yours:

        string Query = @"select a1, a2, a3, a4 from table1 where a1 in 
                               (select b1 from table2 where b2 = @start or b2 = @end)";
    
                using (SqlCommand Comm = new SqlCommand(Query, Conn))
                {
                    Comm.Parameters.Add("@start", SqlDbType.NVarChar).Value = start;
                    Comm.Parameters.Add("@end", SqlDbType.Int).Value = end;
                }