How to update an xml string into a database without changing from double quotes to single quotes?
-
22-04-2021 - |
Question
I need to update part of an xml string in a database, but I do not want to change from double quotes to single quotes, in other words, I want to preserve the double quotes in the xml string. This question is based of another question I had found here
The following:
ExecuteNonQuery("Update Logs
SET Message = '" + encryptedMessage.Replace('"','\'') + "'
WHERE ID = " + message.Id);
Will replace the double quotes with single quotes and save that to the db, but I do not want to permanently change the quotes.
I am trying this:
string sqlUpdate = "Update Logs SET Message = @Message where Id = @Id";
SqlParameter id = new SqlParameter("@Id", message.Id);
SqlParameter msg = new SqlParameter("@Message", message.Msg);
Collection parameters = new Collection();
parameters.Add(id);
parameters.Add(msg);
Data.ExecuteNonQuery(sqlUpdate,parameters);
Data.ExecuteNonQuery
already takes care of the connection for me.
I noticed the sql passed into the ExecuteNonQuery method is Update Logs SET Message = @Message where Id = @Id
I am just using Collection because this the method took a VBCollection.
Solution
Use a parametrized query instead and pass in your XML as a SqlParameter
:
string sqlUpdate = "Update Logs set Message = @MESSAGE where ID = @ID";
using (SqlCommand cmd = new SqlCommand(sqlUpdate, someConnection))
{
cmd.Parameters.Add(new SqlParameter("@MESSAGE", SqlDbType.Xml)).Value = encryptedMessage;
cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)).Value = message.Id;
cmd.ExecuteNonQuery();
}