C#中从数据库查询记录的方法分类( 一般使用两种方法):

时间:2023-01-22 07:06:38

        一种是通过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,myconnection);
    //通过SqlCommand的ExecuteReader()方法构造DataReader 对象。
SqlDataReader myreader=mycommand.ExecuteReader();
while(myreader.read()){
Console.WriteLine(myreader.GetInt32(0)+","+myreader.GetString(1));

  }
myreader.Close();
myconnection.Close();

  }

  }

  }