c# - Preventing SQL injection on insert -


i looking tips prevent sql injection. told on forum code not safe , looking nice enough me fix that.

i have webform , on submit goes aspx.cs page , inserts data ms sql database.

protected void submit_click(object sender, eventargs e)     {         string fullstarttime = starttimehourlist.selectedvalue + ":" + starttimeminutelist.selectedvalue + " " + starttimeamlist.selectedvalue;         string fullendtime = endtimehourlist.selectedvalue + ":" + endtimeminutelist.selectedvalue + " " + endtimeamlist.selectedvalue;          oledbconnection conn;         oledbcommand cmd;         conn = new system.data.oledb.oledbconnection("");         cmd = new system.data.oledb.oledbcommand();         conn.open();         cmd.connection = conn;         var sql = string.format(@"insert formtable1 (nonprofit, contact, phone, email, event, startdate, enddate, starttime, endtime, place, comments, submitdate) values                                                              ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')",                                                            nonprofittxtbox.text, contacttxtbox.text, phonetxtbox.text, emailtxtbox.text, eventtxtbox.text,                                                            startdatetxtbox.text, enddatetxtbox.text, fullstarttime, fullendtime, placetxtbox.text, commentstxtbox.text, datetime.now);         cmd.commandtext = sql;         cmd.executenonquery();         conn.close();  } 

the straightforward fix not build sql concatenating strings together, , instead using params. if you're using sqlcommand can following, otherwise @marcb suggested

sqlcommand cmd = new sqlcommand("insert dbo.table (field1, field2, field3) values (@f1, @f2, @f3)", conn);  cmd.paramters.add("@f1", sqldbtype.varchar, 50).value = "abc"; cmd.paramters.add("@f2", sqldbtype.int).value = 2; cmd.paramters.add("@f3", sqldbtype.varchar, 50).value = "some other value"; 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -