c# - Why won't my code write to SQL? -
i'm writing app store texts sql database, code throws exception saying "the variable name @par1 has been declared", i'm not sure how working , fixing if possible please =]
offending code below
private void smsgetter() { try { decodedshortmessage[] messages = comm.readmessages(phonemessagestatus.all, phonestoragetype.sim); sqlconnection conn = new sqlconnection("data source=*********;initial catalog=********;user id=**********;password=***********"); sqlcommand com = new sqlcommand(); com.connection = conn; conn.open(); foreach (decodedshortmessage message in messages) { //com.commandtext = ("insert smsarchives(message,blacklist) values ('" + message.data.userdatatext + "', 'yes')"); //com.executenonquery(); com.commandtext = ("insert smsarchives(message,blacklist) values (@par1,@par2)"); com.parameters.addwithvalue("@par1", message.data.userdatatext); com.parameters.addwithvalue("@par2", "yes"); com.executenonquery(); } conn.close(); } catch (exception ex) { log(ex.tostring()); } }
you using same command every iteration, adding parameters each time. try calling
com.parameters.clear();
at end of each loop iteration. pre-create parameters , set .value
per iteration - marginally faster.
also: fix sql injection hole :)
Comments
Post a Comment