c# - Using OR Statement in MySQL Parameter -


i'm trying construct mysql query in c# application, i'm wondering if it's possible use or statement in mysql parameters.

i have list of names, , want check , see names exist in database already. here's short example

list<string> names = new list<string> {"adam", "bob", "cathy"}; //actual list longer mysqlconnection connection = getandopenconnection(); mysqlcommand command = connection.createcommand(); command.commandtext = "select * employees name = @names"; command.parameters.add(new mysqlparameters("@names", string.format("names = {0}", string.join(names, " or name = ")))); //is line legal? 

my original idea construct command text way:

command.commandtext = string.format("select * employees name = '{0}'", string.join(names, "' or name = '")) 

the code give me correct command text want, want prevent sql injection.

can please me out on how construct mysqlcommand properly?

not easily, no. need make in query, pain parameterization (which should do). basically, have 2 options:

  • build appropriate command , parameters based on array size
  • use tool you

the latter easier; "dapper", just:

connection.query("select * employees name in @names", new { names })           .tolist(); 

(which list<dynamic>; if have employee class matches columns, can use connection.query<employee>(...).tolist() list<employee> instead).

the former, though, more (for simple version):

var sb = new stringbuilder("select * employees name=@name0"); cmd.parameters.addwithvalue("name0", names[0]); for(int = 1; < names.count ; i++) {     sb.append(" or name=@name").append(i);     cmd.parameters.addwithvalue("name" + i, names[i]); } cmd.commandtext = sb.tostring(); 

there few other ways of doing too:

switch(names.count) {     case 0: cmd.commandtext = "select * employees"; break;     case 1:         cmd.commandtext = "select * employees name=@name";         cmd.parameters.addwithvalue("name", names[0]);         break;     default:         var sb = new stringbuilder(             "select * employees name in (@name0")         cmd.parameters.addwithvalue("name0", names[0]);         for(int = 1;i<names.count;i++) {             sb.append(",@name").append(i);             cmd.parameters.addwithvalue("name" + i, names[i]);         }         cmd.commandtext = sb.append(")").tostring();         break; } 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -