我想从我的代码中删除手动转义。取而代之,我想使用SqlParameter对象。如何在循环中添加SqlParameters?
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();
}
}
[你有什么尝试](http://whathaveyoutried.com)?请解释你卡在哪里。 – Oded
我不想做Replace(“'”,“''”)。而不是我想要使用SqlParameters来添加newMessage和oldMessage命令。 – Vytalyi
是的,我明白你_want_。我在问你是什么**尝试**。 – Oded