asp.net/ sql how can i save the text in Server.GetLastError() to DB when it has single quotes inside the string? -
i have below code , find text value represented in server.getlasterror
contains single quotes , breaks sql insert code.
exception ex = server.getlasterror(); stringbuilder thebody = new stringbuilder(); thebody.append("error message: " + ex.tostring() + "\n"); server.clearerror(); try { string ssql = "insert pmisweberr values ('" + thebody.tostring() + "', getdate())"; using (system.data.sqlclient.sqlconnection con = star.global.getconnection()) { system.data.sqlclient.sqlcommand cmd = new system.data.sqlclient.sqlcommand(ssql, con); cmd.commandtype = system.data.commandtype.text; cmd.executescalar(); } } catch (exception exe) { response.redirect("~/default.aspx?err="+ exe.message.tostring() ); }
string ssql = "insert pmisweberr values (@errval, getdate())"; using (system.data.sqlclient.sqlconnection con = star.global.getconnection()) { system.data.sqlclient.sqlcommand cmd = new system.data.sqlclient.sqlcommand(ssql, con); cmd.commandtype = system.data.commandtype.text; cmd.parameters.addwithvalue( "@errval", thebody.tostring() ); cmd.executescalar(); }
you should use parameters in sql statements. not handle cases such strings single-quotes, helps protect against sql injection attacks.
Comments
Post a Comment