getting Error while executing this query , because column text may contain text with single quotes also. How can i use this query w/o any error
My code is
public bool updateCMStable(int id, string columnName, string columnText)
{
try
{
string sql = "UPDATE CMStable SET " + columnName +
"='" + columnText + "' WHERE cmsID=" + id;
int i = SqlHelper.ExecuteNonQuery(Connection.ConnectionString,
CommandType.Text,
sql);
if (i > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ee)
{
throw ee;
}
}
To fix your code, escape all single quotes with an additional single quote. However I agree with Oded… you need to be using a parameterized query, or possibly a stored proc.
I made some additional corrections to your code.
throwby itself, or you’ll reset the stack trace. Don’t usethrow ee;Edit:
The error you posted is happening because the length of the data being passed in is longer than the specified length of the column. Since you’re using dynamic SQL, the only way around it that I can see is to use a case statement. Each field may have a different size, or maybe not, but the string will have to be truncated to fit to avoid the error. If all the field sizes are the same, you won’t need the case statement.