How to view "Commandtext" with the added parameters?

Asked

Viewed 62 times

3

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 executed Debug.WriteLine(comm.CommandText) my return is:

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

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

  • I don’t think so, you’d have to simulate doing the Places, take a look here https://stackoverflow.com/questions/265192/get-the-generated-sql-statement-from-a-sqlcommand-object

1 answer

0

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 in MYSQLCOMMAND, it will open the parameters taking the name of each one along with the values passed and mount a string. I hope I’ve helped!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.