c# - SQL Query with single quotes -
getting error while executing query , because column text may contain text single quotes also. how can use query w/o error code is
public bool updatecmstable(int id, string columnname, string columntext) { try { string sql = "update cmstable set " + columnname + "='" + columntext + "' cmsid=" + id; int = sqlhelper.executenonquery(connection.connectionstring, commandtype.text, sql); if (i > 0) { return true; } else { return false; } } catch (exception ee) { throw ee; } }
to fix code, escape single quotes additional single quote. however agree oded... need using parameterized query, or possibly stored proc.
public bool updatecmstable(int id, string columnname, string columntext) { if(!string.isnullorempty)) { switch(columnname) { // todo: change 50 & 100 real sizes of columns, // , column names too... case "column1": if(columntext.length > 50) columntext = columntext.substring(0, 50); break; case "column2": if(columntext.length > 100) columntext = columntext.substring(0, 100); break; etc... } } // replace single quote double single quotes columntext = columntext.replace("'", "''"); string sql = string.format("update cmstable set {0} = '{1}' cmsid={2}", columnname, columntext, id); int = sqlhelper.executenonquery(connection.connectionstring, commandtype.text, sql); return (i > 0); }
i made additional corrections code.
- you can return result of if statement when you're returning true | false
- you don't need catch exceptions if you're going throw in catch block
- if catch exception, meaningful it, , decide rethrow it, use
throw
itself, or you'll reset stack trace. don't usethrow ee
; - replace + type concatination string.format if becomes unreadable.
edit:
the error posted happening because length of data being passed in longer specified length of column. since you're using dynamic sql, way around can see use case statement. each field may have different size, or maybe not, string have truncated fit avoid error. if field sizes same, won't need case statement.
Comments
Post a Comment