none
How to prevent SQL Injection with OR parameters. RRS feed

  • Question

  • Good day,

     

    My method receives an arraylist of string, each string representing the first name of a client.

     

    my SELECT query is SELECT * from table1 and I build my WHERE statement dynamically like that:

     

    if (where == "")

    where += " WHERE ";

    where += " FirstName like " + clientName[i ] + " ";

    }

    else

    {

    where += " OR FirstName like " +  clientName[i ] + " ";

    }

    }

    return where;

    }

     

    to make a long story short, I concat multiple OR FirstName like clientName[i ].

     

    However, i would prefer to do sqlComm.Parameters.AddWithValue(....) but I dont know how to procees, since I dont know the number of OR's that will be in my query. Any idea how to proceed or any better way to do that?

     

    Thank you!

     

    Friday, September 7, 2007 6:06 PM

Answers

  • One fairly simple solution I can think of is create the SqlCommand object first and when you append the where clause add a parameter to the SqlCommand object, like so:

     

     

    if (where == "")

    {

    string paramName = "@p" + sqlCommand.Parameters.Count;

    where += " WHERE ";

    where += " FirstName like " + paramName + " ";

    sqlCommand.Parameters.Add(paramName, ...,clientName[i ]);

    }

    else

    {

    string paramName = "@p" + sqlCommand.Parameters.Count;

    where += " OR FirstName like " +  paramName + " ";

    sqlCommand.Parameters.Add(paramName, ...,clientName[i ]);

    }

    }

    return where;

    }

    Friday, September 7, 2007 8:57 PM