Home > database >  Getting a string from SQL.CommandText
Getting a string from SQL.CommandText

Time:11-02

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.

CodePudding user response:

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());
}
  • Related