using IDataReader to call store procedure with parameters

dan_vitch picture dan_vitch · Jun 1, 2010 · Viewed 14.1k times · Source

I use IDataReader to call stored procedures without parameters. I am not finding examples of how to do this when parameters are present. Does IDataReader handle parameters of stored procedure?

Please provide an example.

Answer

Fredrik Mörk picture Fredrik Mörk · Jun 1, 2010

It's not the IDataReader that deals with parameters, that would be the IDbCommand (using the CreateParameter method). Then you can get hold of a reader for the command using the ExecuteReader method.

I put together a simple example:

private static void ExecuteCommand(IDbConnection conn)
{
    using (IDbCommand cmd = conn.CreateCommand())
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "ProcedureName";
        IDataParameter param = cmd.CreateParameter();
        param.ParameterName = "@parameterName";
        param.Value = "parameter value";
        cmd.Parameters.Add(param);
        using (IDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // get data from the reader
            }
        }
    }
}