How do I bind SqlCommand Parameters when using XML field modify() in C#
I'm having trouble escaping SQL for use in a XML field with the modify() function:
example code:
new SqlCommand("UPDATE Table " +
"SET xmlField.modif开发者_如何学JAVAy('insert " + xml_string + " as last into (/element)[1]') " +
"WHERE id = @id", conn, transaction);
@id can be bound in C# by SqlCommand.Parameters.Add(..), but xml_string, being inside the modify method, will not allow parameter binding.
So if I want to protect from SQL injection, what do I do with this xml_string? Is there an SQL Escape method similar to System.Security.SecurityElement.Escape() ?
O.k. I finally got it to work:
new SqlCommand("UPDATE Table " +
"SET xmlField.modify('insert sql:variable(\"@xml_string\") as last into (/element)[1]') " +
"WHERE id = @id", conn, transaction);
and then in the parameter binding, be sure to use the XML data type and not Char (!), otherwise it won't work:
cmd.Parameters.Add("@xml_string", SqlDbType.XML).Value = xml_string;
精彩评论