c# – How to view "CommandText" with added parameters?

Question:

MySqlCommand comm = new MySqlCommand("", conexao);
comm.CommandText = ("SELECT @select FROM @from WHERE @where LIKE '@like'");
comm.Parameters.AddWithValue("@select", select);
comm.Parameters.AddWithValue("@from", from);
comm.Parameters.AddWithValue("@where", where);
comm.Parameters.AddWithValue("@like", like);

If I run Debug.WriteLine(comm.CommandText) my return is:

"SELECT @select FROM @from WHERE @where LIKE '@like'" .

How to view MYSQL connector CommandText for C# with added parameters?

Answer:

You could create an extended method to solve this problem see below:

public static string GravaLog(this IDbCommand cmd)
    {
        int i = 0;
        StringBuilder builder = new StringBuilder();

        var nome = cmd.CommandText.ToString();
        builder.Append(DateTime.Now.ToString() + $" {nome}(");

        foreach (IDataParameter item in cmd.Parameters)
        {

            if (i+1 == cmd.Parameters.Count)
            {
                builder.Append($"{item.ParameterName} => '{item.Value.ToString()}'");
                i++;
            }
            else
            {
                builder.Append($"{item.ParameterName} => '{item.Value.ToString()}', ");
                i++;
            }
        }

        builder.Append(");");
       return builder.toString();
    }

In this case you will receive an IDbCommand that is inherited from MYSQLCOMMAND, it will open the parameters taking the name of each one along with the values ​​passed and assemble a string. Hope this helps!!!

Scroll to Top