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.
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.
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.
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.
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.
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
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With