I want to remove manual escaping from my code. Instead of this I want to use SqlParameter object.
foreach (ThreadPost post in ThreadPosts)
{
string newMessage = Clean(post.Message);
string oldMessage = post.Message;
// escape ' character for prevent errors in SQL script
// I want to pass newMessage and oldMessage as an SqlParameters to prevent unexpected changes, but how it could be done based on the code bellow???
newMessage = newMessage.Replace("'", "''");
oldMessage = oldMessage.Replace("'", "''");
cmdText += string.Format("INSERT INTO ThreadCleanup VALUES ({0}, {1}, '{2}', '{3}')",
post.ID.ToString(),
"NULL",
oldMessage,
newMessage);
}
}
if (!string.IsNullOrEmpty(cmdText))
{
using (SqlConnection con = new SqlConnection(CONNSTR))
{
con.Open();
SqlTransaction tran = con.BeginTransaction(IsolationLevel.ReadUncommitted);
try
{
using (SqlCommand cmd = new SqlCommand(cmdText, con, tran))
{
cmd.ExecuteNonQuery(); // updated records
}
tran.Commit();
}
catch (SqlException ex)
{
tran.Rollback();
}
con.Close();
}
}
You can do it roughly the same way that you do now – by formatting an
insertin a loop, but instead of using one insert per the new/old pair, use one statement for all pairs. You should use column names explicitly to avoid relying on the column order in the table (a big no-no in production) and to avoid creating the second parameter in a loop, even though you always send aNULLto it.At this point, you have a SQL string that looks like this:
You also have a list of
Tuple<long,string,string>for each of the parameters, so you can do this:The advantage of doing it in one go is that you make a single round-trip to your database no matter how many records you must insert. Other than that, the solution follows the same pattern as your current one, so the performance should be comparable.