在C#中使用XML字段modify()时如何绑定SqlCommand参数

时间:2011-05-09 13:44:48

标签: c# xml prepared-statement xquery sqlcommand

我无法使用modify()函数转义SQL以在XML字段中使用:

示例代码:

new SqlCommand("UPDATE Table " +
  "SET xmlField.modify('insert " + xml_string + " as last into (/element)[1]') " +
  "WHERE id = @id", conn, transaction);

@id可以通过SqlCommand.Parameters.Add(..)绑定在C#中,但是在modify方法中的xml_string将不允许参数绑定。

因此,如果我想防止SQL注入,我该如何处理这个xml_string?是否存在类似于System.Security.SecurityElement.Escape()的SQL Escape方法?

1 个答案:

答案 0 :(得分:0)

O.k。我终于开始工作了:

new SqlCommand("UPDATE Table " +
  "SET xmlField.modify('insert sql:variable(\"@xml_string\") as last into (/element)[1]') " +
  "WHERE id = @id", conn, transaction);

然后在参数绑定中,一定要使用XML数据类型而不是Char(!),否则它将无效:

cmd.Parameters.Add("@xml_string", SqlDbType.XML).Value = xml_string;