1

Is there an easy way to get the actual SQL query that is sent from a parametrized CommandText?

If I have

mySQLCommand.CommandText = ("UPDATE dbo.Users SET LimitTime=@limitTime WHERE userID=@userID");

how can I save that to a string with the values of limitTime and userID? I need to be able to log the actual SQL sent.

I have tried to do a mySQLCommand.CommandText.toString() but that does not fill in the values.

EDIT: sorry, this is not mySQL, it is for SQL Server. mySQLCommand is just what I called the SqlCommand variable. Did not even think that is could be confusing.

3
  • "I need to be able to log the actual SQL sent." - which is "UPDATE dbo.Users SET LimitTime=@limitTime WHERE userID=@userID". I assume MySQL is similar to SQL Server in this respect. Basically the parameters are not spliced into the query, they are sent in binary alongside the query, not as part of it. I doubt there is a way to produce an equivalent SQL query built into the library. Commented Nov 2, 2022 at 6:37
  • Also the .ToString() part of CommandText.ToString() is redundant because CommandText is a string. Commented Nov 2, 2022 at 6:38
  • see enter link description here for details Commented Nov 2, 2022 at 7:46

1 Answer 1

1

I assume MySQL is similar to SQL Server. In SQL Server, the parameterized query is sent to the SQL Server as the equivalent of a prepared statement. When you execute the command, the parameters and the query text are treated separately. At no point in time, a complete SQL string is generated.

Try this,you can construct the string yourself like this

string query = mySQLCommand.CommandText;

foreach (SqlParameter p in cmd.Parameters)
{
    query = query.Replace(p.ParameterName, p.Value.ToString());
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is what I was wondering. I was not sure if the SQL string got created on the client or is the server was responsible for some magic. Thanks for clearing it up.
@markdem Someone has downgraded my answer :P anyway happy to help you. try to use a profiler it will be clear

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.