mysql idata有什么用,C#的IDataReader SqlDataReader的区别

Can someone tell me the difference between these two pieces of code? Why use IDataReader?

using (IDataReader reader = cmd.ExecuteReader())

{

while (reader.Read())

{

// get data from the reader

}

}

using (SqlDataReader reader = cmd.ExecuteReader())

{

while (reader.Read())

{

// get data from the reader

}

}

解决方案

SqlDataReader implements the interface IDataReader. So do all other ADO.NET drivers (Oracle, MySql, etc). You can use IDataReader, so that if you plan to change database engine some day, you don't have to rewrite all your SqlDataReader references.

The same goes for IDbConnection, IDbCommand, etc. Of course when creating the connection, you'll need to specify what engine you're using, but aside from that you'll never have to explicitly define which database engine you're using.

Note that IDataReader does not have the HasRows property, and you have to use the Create...() methods to create Commands and Parameters:

IDbCommand command = myDbConnection.CreateCommand();

Instead of:

SqlCommand command = new SqlCommand(myDbConnection);

EDIT: Instead of using the interfaces you may want to use the abstract class DbConnection all ADO.NET providers inherit from. They provide some additional features such as getting schema information, and the aforementioned HasRows property for the DbDataReader. See http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/759fa77b-8269-4c4a-be90-3c2bdce61d92/ for why the interface hasn't kept up with the abstract class.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值