2

我从 xml 格式的数据库中获取字符串,并尝试使用以下查询更新 xml:

ExecuteNonQuery("Update Logs SET Message = " + encryptedMessage + " WHERE ID = " + message.Id);

但它给了我错误信息:

Incorrect syntax near '<'. The label 'xmlns' has already been declared. Label names must be unique within a query batch or stored procedure. An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name. An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name. An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name. An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name. An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.

我觉得这可能与引号有关,但我不确定。我尝试了不同的选项,如单引号、混合等。

例如,如果我这样做:

ExecuteNonQuery("Update Logs SET Message = " + encryptedMessage.Replace('"','\'')+ " WHERE ID = " + message.Id);

这是否会将消息中的双引号永久更新为单引号。我不想这样做。

4

3 回答 3

4

是的,您似乎缺少消息周围的引号:

ExecuteNonQuery("Update Logs SET Message = '" + encryptedMessage + "' WHERE ID = " + message.Id);

XML 本身可能也有单引号,因此您可能需要转义这些(例如,将消息中的一个单引号更改为两个单引号)

于 2012-02-03T17:08:14.960 回答
2

改用参数化查询和命令对象,您的 encryptedMessage 可能包含破坏 UPDATE 语句语法的字符。

于 2012-02-03T17:06:50.620 回答
2

正如@Tomek 提到的,您应该使用参数化查询。它更安全,无需进行@Dan Sueava 的回答中建议的转换。

    SqlCommand command = 
     new SqlCommand("Update Logs SET Message = @EncryptedText WHERE ID = @MessageId");
    command.Parameters.AddWithValue("@EncryptedText", encryptedMessage);
    command.Parameters.AddWithValue("@MessageId", message.Id);

    command.ExecuteNonQuery();
于 2012-02-03T17:35:58.577 回答