Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using IDataReader to call store procedure with parameters

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.

like image 760
dan_vitch Avatar asked Jun 01 '10 21:06

dan_vitch


People also ask

Is DataReader faster than DataSet?

DataReader provides faster performance, but has read-only and forward-only access. DataSet, on the other hand, is high resource-consuming, but offers more control and a disconnected nature.

What is ExecuteReader ()?

ExecuteReader() Sends the CommandText to the Connection and builds a SqlDataReader. ExecuteReader(CommandBehavior) Sends the CommandText to the Connection, and builds a SqlDataReader using one of the CommandBehavior values.

Which function of DataReader is used to get the data from it?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.

How does DataReader work in C#?

A data reader provides an easy way for the programmer to read data from a database as if it were coming from a stream. The DataReader is the solution for forward streaming data through ADO.NET. The data reader is also called a firehose cursor or forward read-only cursor because it moves forward through the data.


1 Answers

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
            }
        }
    }
}
like image 140
Fredrik Mörk Avatar answered Oct 11 '22 21:10

Fredrik Mörk