the regex below not need:
regex.replace(value.tostring(), "[^0-9a-za-z]+", "")
i need remove escape characters string because creating 1 sql string , when have character '
or \r\n
etc. sql generates error, cannot use : sqlparameter in case have list of sqls in string, can remove characters don't want.
so, need remove these characters:
\r \n ' /\
added codes requested:
private static string convertwhetherusescomas(object value) { // formats comas or not if (value string) { // fix problem break characters such \/`' value = string.format("'{0}'", regex.replace(value.tostring(), "[^0-9a-za-z]+", "")); } else if (value datetime) { value = string.format("'{0}'", value.safetodatetime(null).value.tostring("yyyy-mm-dd hh:mm:ss tt")); } else if (value == null) { value = "null"; } else if (value boolean) { value = value.safetobool(false) == false ? 0 : 1; } return value.tostring(); } private static list<string> convertdiferencestosql<t>(differences<t> differences, string tablename, string primarykey) t : ihasid<int> { var result = new list<string>(); differences.new.tolist().foreach(newitem => { var fieldnames = new stringbuilder(); var fieldvalues = new stringbuilder(); var properties = newitem.gettype().getproperties().tolist(); properties.foreach(f => { var propertyname = f.name.toupper() == "id" ? primarykey : f.name; var propertyvalue = convertwhetherusescomas(f.getvalue(newitem)); if (propertyvalue == "null") return; // ignores null values fieldnames.appendformat("{0},", propertyname); fieldvalues.appendformat("{0},", propertyvalue); }); var sqlfields = fieldnames.tostring(0, fieldnames.length - 1); var sqlvalues = fieldvalues.tostring(0, fieldvalues.length - 1); result.add(string.format("insert {0} ({1}) values ({2});", tablename, sqlfields, sqlvalues)); }); differences.changed.foreach(changedrecord => { var fields = new stringbuilder(); changedrecord.changedfields.foreach(changedfield => { var propertyname = changedfield.property == "id" ? primarykey : changedfield.property; var propertyvalue = convertwhetherusescomas(changedfield.newvalue); fields.appendformat("{0}={1},", propertyname, propertyvalue); }); var sqlfields = fields.tostring(0, fields.length - 1); result.add(string.format("update {0} set {1} {2}={3};", tablename, sqlfields, primarykey, changedrecord.id)); }); differences.deleted.foreach(deleteditem => result.add(string.format("delete {0} {1}={2};", tablename, primarykey, deleteditem.getid()))); return result; }
you can place these characters character class, , replace string.empty
:
var rgx4 = new regex(@"[\r\n'/\\]"); var tst = "\r \n ' /\\"; tst = rgx4.replace(tst, string.empty);
result:
a character class executes faster, alternative list, there lot of back-tracking impeding performance.