none
How to prevent SQL Injection with dynamic WHERE statements? RRS feed

  • Question

  • (This subject has also been posted in the ASP.NET section, as I wasnt sure where to post)

     

    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 proceed, 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:12 PM

Answers

  • where = "WHERE 1=2 ";

    for ... {

       where += " or FirstName like @" + i + " ";

       sqlComm.Parameters.AddWithValue("@"+i, clientName[ i ]) ;

    }

    Friday, September 7, 2007 7:28 PM

All replies

  •  

    use a StringBuilder object rather than the += on a string.
    Friday, September 7, 2007 6:22 PM
  • Thank you Ryan, but my question was more about the parameter things.

     

    Good  observation though, ill use the StringBuilder. But back to my question, what do to with the parameter thing?

    Friday, September 7, 2007 6:56 PM
  • where = "WHERE 1=2 ";

    for ... {

       where += " or FirstName like @" + i + " ";

       sqlComm.Parameters.AddWithValue("@"+i, clientName[ i ]) ;

    }

    Friday, September 7, 2007 7:28 PM