0

I had a Program in c# which would run queries using a dynamically created string which would be used as a query.

Now due to possibility of SQL injection, I want to use parameterized queries to generate the same.

Was looking at Parameterized dynamic sql query and that is mostly what I want, but then I want multiple parameters in the same sequence and not in different sequences. i.e I want something like

(Where value in ({0}, {1}, {2}), param0 , param1, param2 )

The answer in that thread is

SqlCommand cmd = new SqlCommand();
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.Append("SELECT name, memberid FROM members ");

var i = 1;
foreach (string item in keywords)
{
    sqlBuilder.Append(i == 1 ? " WHERE " : " AND ");
    var paramName = "@searchitem" + i.ToString();
    sqlBuilder.AppendFormat(" Name LIKE {0} ", paramName); 
    cmd.Parameters.AddWithValue(paramName, "%" + item + "%");

    i++;
}
cmd.CommandText = sqlBuilder.ToString();

If I use this for my query, this would generate something like

where Value In param0 and value in param1 and value in param2

which if I'm not mistaken is terrible in terms of server performance.

So how do I get something similar to

sqlBuilder.AppendFormat(" Name IN {0} , {1} , {2} ", paramName0 , paramName1 , paramName2 );

for a parameterized dynamic query?

All the methods that I have tried compiles ok, but then returns run time errors.

Can't seem to figure what I'm doing wrong. :( Any help?

4
  • Do you need to support multiple flavors of database engines or are you only targeting MS SQL Server ? Commented May 23, 2016 at 13:12
  • 1
    @user957902 OP has mysql in tags... Commented May 23, 2016 at 13:15
  • Need to support MySQL only. (No MS SQL). Commented May 23, 2016 at 13:34
  • @Alex Monday morning and not enough caffeine intake yet :P Commented May 23, 2016 at 15:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.