Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting SQL query string from DbCommand with Parameters

Tags:

c#

sql

mysql

Just before executing a SQL query on a MySQL database in C# I want to log the query that will be executed. What I have now obviously only logs SELECT * FROM foo WHERE Id = @Id where I would like to see SELECT * FROM foo WHERE Id = 5. How do I do that?

    DbCommand dbCommand = dbFactory.CreateCommand();
    dbCommand.CommandText = "SELECT * FROM foo WHERE Id = @Id";

    DbParameter param = dbCommand.CreateParameter();
    param.ParameterName = "@Id";
    param.Value = 5;

    dbCommand.Parameters.Add(param);

    dbConnection.Open();
    Log.AddVerbose(String.Format("SQL query: {0}", dbCommand.CommandText));
    dbCommand.ExecuteReader();
like image 765
BioGeek Avatar asked Jun 18 '14 16:06

BioGeek


People also ask

How do I get query string in SQL Server?

Dynamic SQL lets you create a query string based off of user input. SQL Server allows you to create dynamic SQL statements. The statements use a SQL string varchar data type, then you execute the command. Even though the SQL value is a string, SQL Server executes the string as if it is SQL code.

How do you use parameters in Ado?

When adding parameters, you must supply a ParameterDirection property for parameters other than input parameters. The following table shows the ParameterDirection values that you can use with the ParameterDirection enumeration. The parameter is an input parameter. This is the default.

What is parameterized SQL query?

Parameterized SQL queries allow you to place parameters in an SQL query instead of a constant value. A parameter takes a value only when the query is executed, which allows the query to be reused with different values and for different purposes.


1 Answers

If you are trying to log you can do an extension method like this.

public static string GetGeneratedQuery(this SqlCommand dbCommand)
{
    var query = dbCommand.CommandText;
    foreach (var parameter in dbCommand.Parameters)
    {
            query = query.Replace(parameter.ParameterName, parameter.Value.ToString());
    }

    return query;
}

And you can use it like this.

Log.AddVerbose(String.Format("SQL query: {0}", GetGeneratedQuery(dbCommand)));
like image 143
Anuraj Avatar answered Sep 22 '22 02:09

Anuraj