揭开ADO.NET神秘面纱——ADO.NET结构综述
ADO.NET提供了两个主要的组件来访问和操作数据,它们分别是.NET Framework 数据提供程序和 DataSet,为了更好的进行数据库的程序设计,我们非常有必要了解下ADO.NET的工作机制。

.NET Framework 数据提供程序是专门为数据操作以及快速、只进、只读访问数据而设计的组件。
Connection 对象提供到数据源的连接。 使用 Command 对象可以访问用于返回数据、修改数据、运行存储过程以及发送或检索参数信息的数据库命令。 DataReader 可从数据源提供高性能的数据流。 最后,DataAdapter 在 DataSet 对象和数据源之间起到桥梁作用。 DataAdapter 使用 Command 对象在数据源中执行 SQL 命令以向 DataSet 中加载数据,并将对 DataSet 中数据的更改协调回数据源。
下面用代码列表演示如何使用SQLServer、OLE DB、ODBC的 ADO.NET 技术从数据库中检索数据
SqlClient假定可以连接到 Microsoft SQL Server 的 Northwind 示例数据库。代码创建一个 SqlCommand 以从 Products 表中选择行,并添加 SqlParameter 来将结果限制为其 UnitPrice 大于指定参数值的行。 SqlConnection 在 using 块内打开,这将确保在代码退出时会关闭和释放资源。示例代码使用 SqlDataReader 执行命令,并在控制台窗口中显示结果。
Option Explicit OnOption Strict OnImports System.DataImports system.Data.SqlClientPublic Class NorthwindDataSet Public Shared Sub Main() Dim connectionString As String = _ GetConnectionString() ConnectToData(connectionString) End Sub Private Shared Sub ConnectToData(ByVal connectionString As String) Using connection As SqlConnection = New SqlConnection(connectionString) Dim suppliersAdapter As SqlDataAdapter =New SqlDataAdapter() suppliersAdapter.TableMappings.Add("Table", "Suppliers") connection.Open() Console.WriteLine("The SqlConnection is open.") Dim suppliersCommand As SqlCommand = New SqlCommand( "SELECT SupplierID, CompanyName FROM dbo.Suppliers;",connection) suppliersCommand.CommandType = CommandType.Text suppliersAdapter.SelectCommand = suppliersCommand Dim dataSet As DataSet = New DataSet("Suppliers") suppliersAdapter.Fill(dataSet) Dim productsAdapter As SqlDataAdapter = New SqlDataAdapter() productsAdapter.TableMappings.Add("Table", "Products") Dim productsCommand As SqlCommand = New SqlCommand("SELECT ProductID, SupplierID FROM dbo.Products;"connection) productsAdapter.SelectCommand = productsCommand productsAdapter.Fill(dataSet) connection.Close() Console.WriteLine("The SqlConnection is closed.") Dim parentColumn As DataColumn = dataSet.Tables("Suppliers").Columns("SupplierID") Dim childColumn As DataColumn = dataSet.Tables("Products").Columns("SupplierID") Dim relation As DataRelation = New System.Data.DataRelation("SuppliersProducts",parentColumn, childColumn) dataSet.Relations.Add(relation) Console.WriteLine("The {0} DataRelation has been created.", relation.RelationName) End Using End Sub Private Shared Function GetConnectionString() As String Return "Data Source=(local);Initial Catalog=Northwind;" & "Integrated Security=SSPI;" End FunctionEnd Class
在决定应用程序应使用 DataReader还是应使用 DataSet时,应考虑应用程序所需的功能类型。 使用 DataSet 可执行以下操作:
如果不需要 DataSet 所提供的功能,则可以通过使用 DataReader 以只进、只读方式返回数据,从而提高应用程序的性能。 虽然DataAdapter 使用 DataReader 来填充DataSet 的内容,但使用 DataReader 可以提升性能,因为这样可以节省 DataSet 所使用的内存,并将省去创建 DataSet 并填充其内容所需的处理。