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?

Noctis
  • 11,507
  • 3
  • 43
  • 82
  • See this [question](http://stackoverflow.com/questions/5356467/from-net-can-i-get-the-full-sql-string-generated-by-a-sqlcommand-object-with-s) Times ago I have used the code and it worked perfectly – Tinwor Nov 25 '13 at 23:35

2 Answers2

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());
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
  • :) . 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 :) – Noctis Nov 25 '13 at 23:56
  • @Sudhakar Tillapudi, This does not work in Ubuntu 16.04 with cmd.Parameters.AddWithValue("@some_value", some_string_here); Thank you. – Frank Jul 18 '16 at 01:06
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.)

Community
  • 1
  • 1
ispiro
  • 26,556
  • 38
  • 136
  • 291
  • Just when you expect something to be simple and straight forward ... meh ... good answer in the links provided. Cheers for that. – Noctis Nov 25 '13 at 23:57