一种是通过DataReader对象直接访问;另一种则是通过数据集Dataset和Dataadapter对象访问.
使用ADO.NET的Datareader对象能从数据库中检索数据。检索出来的数据形成一个只读只进的数据流,存储在客户端的网络缓冲区内。 Datareader对象的read方法可以前进到一下条记录。在默认情况下,每执行一次read方法只会在内存中存储一条记录系统的开销非常少。
创建datareader之前必须先创建sqlcommand对象,然后调用该对象的executereader方法来构造sqldatareader对象,而不是直接使用构造函数。
下面的示例程序完成的功能是访问sqlserver数据库,并使用datareader从northwind数据中读取记录,并将查询结果通过控制台输出。
using System;
using System.Data;
using System.Data.SqlClient;
namespace ReadDataFromDB{
class Class1{
static void Main(string[] args){
string myconn="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind";
//需要执行的SQL语句
string mysql="select OrderID,CustomerID from Orders where CustomerID='CHOPS'";
//打开数据库连接。
SqlConnection myconnection=new SqlConnection(myconn);
myconnection.Open();
//创建SqlCommand 对象
SqlCommand mycommand=new(mysql

本文介绍了在C#中从SQL Server数据库查询数据的两种常见方法:使用DataReader对象实现只进数据流,适合大量数据的高效读取;以及通过DataSet和DataAdapter对象,允许在内存中存储完整数据集,方便数据操作。示例代码演示了如何使用DataReader从Northwind数据库读取并打印CustomerID为'CHOPS'的Orders记录。
最低0.47元/天 解锁文章
913

被折叠的 条评论
为什么被折叠?



