A way to see query after parameters are applied?

Mike picture Mike · Oct 14, 2011 · Viewed 17.2k times · Source

In a C# application, I'm building a query by creating a query string with parameters, then to the command adding the parameters and their values. For example:

string query = "UPDATE USERS u SET u.username = @PARM_USERNAME " +
               "WHERE u.id = @PARM_USERID ";

command.Parameters.AddWithValue("@PARM_USERNAME", user.username);
command.Parameters.AddWithValue("@PARM_USERID", user.id);

command.Connection.Open();
int res = command.ExecuteNonQuery();

It would be beneficial to see the query with parameters applied, is this doable in C#/Visual Studio? I can check the command.CommandText, but it's only showing me the same content as the query above, with the parameter placeholders there. If it helps, this is against MySQL.

Answer

If you want to see the query with parameters applied:

string tmp = command.CommandText.ToString();
foreach (SqlParameter p in cmd.Parameters) {
    tmp = tmp.Replace('@' + p.ParameterName.ToString(),"'" + p.Value.ToString() + "'");
}

tmp will then hold the query with the parameters applied. Each parameter will be surrounded by single quotes.

Of course, it is NOT safe to execute. I use it for debugging purposes.