我想从我的代码中删除手动转义。而不是这个我想使用 SqlParameter 对象。
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();
}
}