2

Having code that looks like:

MySqlCommand cmd = new MySqlCommand(
    "SELECT * FROM DB_name_here WHERE some_field =@some_value;"
);

cmd.Parameters.AddWithValue("@some_value", some_string_here);

Can I get it back as a simple string for debug purposes, that says:

SELECT * FROM DB_name_here WHERE some_field =some_string_here;

The obvious cmd.ToString() failed me promptly, returning a MySql.Data.MySqlClient.MySqlCommand.
The cmd.CommandText will return the string with the parameter (@some_value in my case).

Any suggestions?

1
  • See this question Times ago I have used the code and it worked perfectly Commented Nov 25, 2013 at 23:35

2 Answers 2

2

According to this answer it cannot be done directly.

From the answer:

At no point in time a complete SQL string is generated.

(For workarounds see the other answers there. especially https://stackoverflow.com/a/265261/939213.)

Sign up to request clarification or add additional context in comments.

1 Comment

Just when you expect something to be simple and straight forward ... meh ... good answer in the links provided. Cheers for that.
2

You can use CommandText property of MySqlCommand object to get the actual command string . for parameters you can iterate over Parameters and replace with replace the Parameters Parameter Value

Solution:

String commandtext = cmd.CommandText;
foreach (SqlParameter p in cmd.Parameters)
commandtext = commandtext.Replace(p.ParameterName, p.Value.ToString());

2 Comments

:) . You saved me pointing out the bug in your previous version (where you set commandtext = "" . Nice catch. This works ok enough, but like the answer that ispiro pointed out, will leave you with strings not quoted. Cheers for the help never the less :)
@Sudhakar Tillapudi, This does not work in Ubuntu 16.04 with cmd.Parameters.AddWithValue("@some_value", some_string_here); Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.