database - How to avoid SQL Injection with Update command in Npgsql? -
i trying use npgsql postgresql client accomplish 2 things:
- avoid sql injection, and
- manage data containing single quote '
i cannot see how either :(
postrgesql version 9.1
in below code, dx.chronic of type bool? , cdesc of table dx may contain single quote, "tom's dog". clearly, updatecmd, written, fail when npgsql/postgresql hits single quote.
string schronic = (dx.chronic == null) ? "null" : dx.chronic.tostring(); string updatecmd = "update dx "+ "set chronic = " + schronic + " (trim(lower(cdesc)), trim(cicd9)) = "+ " ('"+dx.description.trim().tolower()+"','"+dx.icd9.trim() +"');"; using (npgsqlcommand command = new npgsqlcommand(updatecmd, conn)) { command.parameters.add(new npgsqlparameter("value1", npgsqldbtype.text)); command.parameters[0].value = "big tom's dog"; ....... ? ? ? ? ? ? ? ? ? ? ? ? ? ...................
how done? appreciated.
tia
as @tadman says, should never use string concatenation compose query - source of sql injection. however, there's no need prepare statement. use parameter placeholders in query, following should work:
string updatecmd = "update dx set chronic = @p1 (trim(lower(cdesc)), trim(cicd9)) = (@p2);"; using (npgsqlcommand command = new npgsqlcommand(updatecmd, conn)) { cmd.parameters.addwithvalue("p1", "chronic"); cmd.parameters.addwithvalue("p2", "value"); cmd.executenonquery(); }
Comments
Post a Comment