Use DataReader Cleverly

Introduction

ADO.NET DataReader is a read only and forward only cursor that allows you to iterate through the records very fast. In terms of performance DataReader is possibly the fastest way to fetch and iterate the rows. However, if used incorrectly it can cause some troubles. This article throws light on some of such things to watch for while you code and explains general dos and don'ts about DataReader.

Some facts about the DataReader

Before we go ahead to more details it would be nice to highlight some facts about the DataReader.

  • DataReader is an ADO.NET class that represents a read only and forward only cursor.
  • DataReader classes comes in various flavors based on the underlying data provider. For example, SQL Server data provider has SqlDataReader class that represents DataReader for SQL server.
  • DataReader requires an open connection with the database when you are iterating through it.
  • This means DataReader do not caches any data unlike classic ADO recordset.
  • Since DataReader is very optimized it provides a very fast and efficient way to iterate through the data.
How to use DataReader class?
SqlConnection cnn =
new  SqlConnection
(
@" data source=.vsdotnet;initial catalog=northwind;user id=sa " );
SqlCommand cmd
=
new  SqlCommand( " select * from employees " ,cnn);
cnn.Open();
SqlDataReader dr
= cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr.GetString(
1));
}

dr.Close();
cnn.Close();

 

Above code snippet illustrates the basic use of DataReader class.

  • We created an instance of SqlConnection and SqlCommand classes.
  • We then called ExecuteReader() method of the command object that returns the DataReader.
  • We iterate through the DataReader and print firstname column on the console.
  • We then close the DataReader as well as the connection.

In the next sections we will consider certain scenarios in which incorrect use of DataReader can pose problems to your code.

Stored procedures returning records as well as a return value (or output parameters)

In some cases you may have stored procedures that return records as well as a return value. Following is an example,

 
 
create   procedure  GetEmployees
As
select   *   from  employees;
return   100 ;

Here, we are having a SQL Server stored procedure called GetEmployees that returns all the rows from Employees table and also returns some return value (100). Many times such return values are used to indicate some kind of status to the caller.

In order to call above stored procedure you will write code as shown below:

 

SqlConnection cnn =
new  SqlConnection
(
@" data source=.vsdotnet;initial catalog=northwind;user id=sa " );
SqlCommand cmd
=
new  SqlCommand( " GetEmployees " ,cnn);
cmd.CommandType
= CommandType.StoredProcedure;SqlParameter p1 = new  SqlParameter();
p1.ParameterName
= " @retval " ;
p1.Direction
= ParameterDirection.ReturnValue;cmd.Parameters.Add(p1);
...
...

Here, we added a parameter to the command's Parameters collection. This parameter is for the return value of the stored procedure as indicated by its Direction property. Everything sounds ok till this point. Now, have a look at the code below:

 
 
cnn.Open();
SqlDataReader dr
= cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr.GetString(
1));
}

int  i = ( int )cmd.Parameters[ " @retval " ].Value;
dr.Close();

The code looks similar to our previous example. But if you run this code you will get error - "Object reference not set to an instance of object' at the line where we are fetching the return value. The error is caused because we are trying to retrieve the return value before closing the DataReader. I mentioned earlier that DataReader is like an open cursor with the database. Unless the DataReader is closed your stored procedure will not execute further statements and hence the error. Remedy to this is to close DataReader before you retrieve the return value. Note that similar situation will arise in case of output parameters also.

 

...
dr.Close();
int  i = ( int )cmd.Parameters[ " @retval " ].Value;
...

 

Returning DataReader form components

In many n-tier applications the data access code is isolated in a component (class library). In such cases you get the DataReader as a return value of some method of the component. Following code snippet shows one such example.

 

public  SqlDataReader GetEmployees()
{
SqlConnection cnn
=
new SqlConnection
(
@"data source=.vsdotnet;initial catalog=northwind;user id=sa");
SqlCommand cmd
=
new SqlCommand("select * from employees",cnn);
cnn.Open();
SqlDataReader dr
=cmd.ExecuteReader();
cnn.Close();
return dr;
}

Here, you obtain the DataReader as in previous case by calling ExecuteReader() method and then close the database connection. Finally, you return the DataReader to the caller. Previously I mentioned that DataReader requires a "live" connection with the database. If you close the connection as shown above the caller will not be able to iterate through the DataReader and in fact will get an exception.

To resolve above problem the immediate solution that comes to the mind is - not to close the connection and just return the DataReader to the caller. This way the caller will be able to iterate through the DataRedaer but the underlying connection is kept open! This is certainly a dangerous side effect.

Fortunately, DataReader and Command objects provide a built-in way to tackle this situation. Have a look at the code below:

 

public  SqlDataReader GetEmployees()
{
SqlConnection cnn
=
new SqlConnection
(
@"data source=.vsdotnet;initial catalog=northwind;user id=sa");
SqlCommand cmd
=
new SqlCommand("select * from employees",cnn);
cnn.Open();
SqlDataReader dr
=
cmd.ExecuteReader(CommandBehavior.CloseConnection);
return dr;
}

Noticed the difference? Here, we have use some different flavor of ExecuteReader() method. This time we are passing an enumerated value CommandBehavior.CloseConnection. This instructs the DataReader than when the caller calls Close() method of the DataReader the underlying database connection is also to be closed. 

 

SqlDataReader dr = Class1.GetEmployees();
while (dr.Read())
{
Console.WriteLine(dr.GetString(
1));
}

dr.Close(); 
// closes underlying database connection also.

Note that since calling Close() method on DataReader also closes the underlying connection, you need to open the connection again if you want to execute any more queries.

Using multiple queries in a DataReader

DataReder can also be used to return results of multiple queries. Following example shows how:

 
 
SqlConnection cnn =
new  SqlConnection
(
@" data source=.vsdotnet;initial catalog=northwind;user id=sa " );
SqlCommand cmd
=
new  SqlCommand
(
" select * from employees;select count(*) from employees " ,cnn);
cnn.Open();
SqlDataReader dr
= cmd.ExecuteReader();

Here, we created a command object with CommandText containing two queries. Note that semicolon (;) is statement separator in SQL server (T-SQL). When you get the DataRedar back you can iterate through these two result sets like this:

 

while (dr.Read())
{
//code here
}

// shift to the next result set
dr.NextResult()
// iterate again
while (dr.Read())
{
//code here
}

One of the use of above technique is to retrieve records as well as aggregate functions such as Count, Max or Min.

General recommendations

Considering above pitfalls and features of DataReader (and also from my experience of working with teams) I recommend these things:

  • Use DataReader when you want to quickly scan through the data without much of a processing. DataReader is fastest way when you want to iterate through data.
  • If you want to return records and also want to have output parameters or return values in stored procedures design such stored procedures carefully. Think of some possible alternative.
  • DataReader is fastest when you want to iterate through data and is ideal for data binding with controls such as DataGrid. I have often seen that developers forget to call the Close() method of the DataRedaer. If you are working with big team with novice members, it is  safe to return DataSet instead of DataReader from your components. If you are having strong quality testing and code review standards in place you can stick with the DataReader approach.
  • When you are building components and you don't know at design time how and where exactly they are going to be used it is safe to return DataSet instead of DataReder. Passing DataReader across the system especially through too many layers or classes can cause similar issues discussed above.
Summary

In this article we examined various facets of DataReader class. We saw common pitfalls along with possible solutions.

 
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
应用背景为变电站电力巡检,基于YOLO v4算法模型对常见电力巡检目标进行检测,并充分利用Ascend310提供的DVPP等硬件支持能力来完成流媒体的传输、处理等任务,并对系统性能做出一定的优化。.zip深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值