请输入您要查询的百科知识:

 

词条 DataReader
释义

  1. DataReader Types

  2. Strong vs Weak Typing

  3. Common Errors

  4. Sample Code

  5. References

{{more citations needed|date=September 2017}}

In ADO.NET, a DataReader is a broad category of objects used to sequentially read data from a data source.[1] DataReaders provide a very efficient way to access data, and can be thought of as a Firehose cursor from ASP Classic, except that no server-side cursor is used. A DataReader parses a Tabular Data Stream from Microsoft SQL Server, and other methods of retrieving data from other sources.

A DataReader is usually accompanied by a Command object that contains the query, optionally any parameters, and the connection object to run the query on.

DataReader Types

There is no DataReader class in ADO.NET, but there are a number of classes that implement the IDataReader interface:

  • {{mono|System.Data.SqlClient.SqlDataReader}}
  • {{mono|System.Data.OleDb.OleDbDataReader}}
  • {{mono|Oracle.OracleClient.OracleDataReader}}

DataReaders have a small footprint and good performance because each is tailor-made to the task at hand, however this makes it more difficult to write an application that can be moved from one backend data source to another. Some provider-specific DataReaders expose types used by the underlying database - for example, {{mono|int}} values can be null in Microsoft SQL Server, but not in the .NET Framework prior to version 2.0.

Strong vs Weak Typing

When using a DataReader to retrieve data, the developer can choose to read field values in strongly typed manner ( example: {{code|myReader.GetString(12)}} ) or a weakly typed manner, returning then as {{mono|System.Object}}s ( example: {{code|myReader.GetValue(12)}} ). Both approaches have their pros and cons.

Using the strongly typed retrieval methods can be more cumbersome, especially without specific knowledge of the underlying data. Numeric values in the database can translate to several .NET types: {{mono|Int16, Int32, Int64, Float, Decimal}}, or {{mono|Currency}}. Trying to retrieve a value using the wrong type results in an exception being thrown, which stops code from running further, and slows the application down. This is also true when you use the right type, but encounter a {{mono|DbNull}} value ( this can be avoided by using the {{mono|IsDbNull}} boolean function of the DataReader class ). The benefit to this retrieval method is that data validation is performed sooner, improving the probability of data correction being possible.

Weakly typed data retrieval allows for quick code writing, and allows for the data to be used in some fashion when the developer doesn't know beforehand what types will be returned. Further, with some effort, the programmer can extract the value into a variable of the proper type by using the {{mono|GetFieldType}} or {{mono|GetDataTypeName}} methods of the DataReader.

Common Errors

A DataReader can in some cases be used in place of a DataTable, however many programmers have experienced connection bloat when following this approach. A DataReader can only be used against an (already) open database connection; that connection isn't closed until the DataReader's {{mono|Dispose}} method is called. If an exception is thrown while the data is being processed, for example as described in Strong and weak typing, above, the {{mono|Dispose}} method will never be called if the developer writes code explicitly declaring and disposing the DataReader without the use of a {{mono|try}}-{{mono|finally}} block. The C# {{mono|using}} construct is a good way to avoid this problem, as shown below in the code example.

Sample Code

Sample of accessing SQL Data using DataReader

void DataTest()

{
 using(SqlConnection conn1 = new SqlConnection(...)) {  conn1.Open();  SqlCommand mycommand = new SqlCommand("Select * From someTable", conn1);  using(SqlDataReader myreader = mycommand.ExecuteReader()) {   if(myreader != null)    while(myreader.Read())     Console.WriteLine(myreader.GetValue(0).ToString() + ":" + myreader.GetTypeName(0));
  }  mycommand.Dispose();  }

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.Odbc;

using MySql.Data.MySqlClient;

namespace ConsoleApplication1

{
    class Program    {        static void Main(string[] args)        {            string Conn = "Server=localhost;Uid=root;Pwd=thiru;Database=Employee";            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(Conn);                      MySqlCommand comm = new MySqlCommand("select * from emp",conn);            conn.Open();            //IAsyncResult a;            MySqlDataReader Ada = comm.ExecuteReader();            while (Ada.Read())            {                Console.WriteLine(Ada[0]);            }        }    }

}

References

1. ^{{cite web|title=DataAdapters and DataReaders|url=https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/dataadapters-and-datareaders|website=docs.microsoft.com|publisher=Microsoft|accessdate=4 September 2017|language=en-us}}
{{DEFAULTSORT:Datareader}}{{Portal bar|.NET Framework}}

3 : SQL data access|ADO.NET Data Access technologies|Microsoft application programming interfaces

随便看

 

开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。

 

Copyright © 2023 OENC.NET All Rights Reserved
京ICP备2021023879号 更新时间:2024/11/11 19:25:24