Chinaunix首页 | 论坛 | 博客
  • 博客访问: 669450
  • 博文数量: 90
  • 博客积分: 1631
  • 博客等级: 上尉
  • 技术积分: 1413
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-15 22:43
文章分类
文章存档

2017年(8)

2016年(9)

2015年(11)

2014年(10)

2013年(9)

2012年(9)

2010年(2)

2009年(10)

2008年(22)

我的朋友

分类: C/C++

2014-06-07 17:53:45

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


.NET Framework 数据提供程序

    .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 执行命令,并在控制台窗口中显示结果。

[plain] view plaincopy
  1. Option Explicit On  
  2. Option Strict On  
  3.   
  4. Imports System  
  5. Imports System.Data  
  6. Imports System.Data.SqlClient  
  7.   
  8. Public Class Program  
  9.     Public Shared Sub Main()  
  10.     ' 定义连接字符串,并赋值  
  11.         Dim connectionString As String = "Data Source=(local);Initial Catalog=Northwind;" & "Integrated Security=true"  
  12.   
  13.         ' 提供了插叙字符串  
  14.         Dim queryString As String ="SELECT ProductID, UnitPrice, ProductName from dbo.Products " & "WHERE UnitPrice > @pricePoint " & "ORDER BY UnitPrice DESC;"  
  15.   
  16.         Dim paramValue As Integer = 5  
  17.   
  18.         ' 在Using块中创建和打开连接,确保所有的资源在使用完毕后能够关闭并释放  
  19.         Using connection As New SqlConnection(connectionString)  
  20.   
  21.             ' 创建连接和属性对象  
  22.             Dim command As New SqlCommand(queryString, connection)  
  23.         command.Parameters.AddWithValue("@pricePoint", paramValue)  
  24.   
  25.             ' 在try/catch块中打开连接, 创建和执行数据阅览,把结构显示到控制台窗口  
  26.             Try  
  27.                 connection.Open()  
  28.                 Dim dataReader As SqlDataReader = command.ExecuteReader()  
  29.                 Do While dataReader.Read()  
  30.                     Console.WriteLine(vbTab & "{0}" & vbTab & "{1}" & vbTab & "{2}",dataReader(0), dataReader(1), dataReader(2))  
  31.                 Loop  
  32.                 dataReader.Close()  
  33.   
  34.             Catch ex As Exception  
  35.                 Console.WriteLine(ex.Message)  
  36.             End Try  
  37.             Console.ReadLine()  
  38.         End Using  
  39.     End Sub  
  40. End Class  
  41.   

OleDb

      创建一个 OleDbCommand以从 Products 表中选择行,并添加一个 OleDbParameter来将结果限制为其 UnitPrice 大于指定参数值的行。 OleDbConnection在 using 块内打开,这将确保在代码退出时会关闭和释放资源。 示例代码使用 OleDbDataReader 执行命令,并在控制台窗口中显示结果。

[plain] view plaincopy
  1. Option Explicit On  
  2. Option Strict On  
  3.   
  4. Imports System  
  5. Imports System.Data  
  6. Imports System.Data.OleDb  
  7.   
  8. Public Class Program  
  9.     Public Shared Sub Main()  
  10.   
  11.         Dim connectionString As String ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & "c:\Data\Northwind.mdb;User Id=admin;Password=;"  
  12.   
  13.        ' 提供了插叙字符串  
  14.         Dim queryString As String = "SELECT ProductID, UnitPrice, ProductName from Products " & "WHERE UnitPrice > ? " & "ORDER BY UnitPrice DESC;"  
  15.   
  16.         ' Specify the parameter value.  
  17.         Dim paramValue As Integer = 5  
  18.   
  19.         '在Using块中创建和打开连接,确保所有的资源在使用完毕后能够关闭并释放          
  20.     Using connection As New OleDbConnection(connectionString)  
  21.   
  22.             Dim command As New OleDbCommand(queryString, connection)  
  23.             command.Parameters.AddWithValue("@pricePoint", paramValue)  
  24.   
  25.             Try  
  26.                 connection.Open()  
  27.                 Dim dataReader As OleDbDataReader = _  
  28.                  command.ExecuteReader()  
  29.                 Do While dataReader.Read()  
  30.                     Console.WriteLine( _  
  31.                         vbTab & "{0}" & vbTab & "{1}" & vbTab & "{2}", _  
  32.                      dataReader(0), dataReader(1), dataReader(2))  
  33.                 Loop  
  34.                 dataReader.Close()  
  35.   
  36.             Catch ex As Exception  
  37.                 Console.WriteLine(ex.Message)  
  38.             End Try  
  39.             Console.ReadLine()  
  40.         End Using  
  41.     End Sub  
  42. End Class  
  43.   

Odbc

    创建一个 OdbcCommand以从 Products 表中选择行,并添加一个 OdbcParameter来将结果限制为其 UnitPrice 大于指定参数值的行。 OdbcConnection在 using 块内打开,这将确保在代码退出时会关闭和释放资源。 示例代码使用 OdbcDataReader 执行命令,并在控制台窗口中显示结果。


[plain] view plaincopy
  1. Option Explicit On  
  2. Option Strict On  
  3.   
  4. Imports System  
  5. Imports System.Data  
  6. Imports System.Data.Odbc  
  7.   
  8. Public Class Program  
  9.     Public Shared Sub Main()  
  10.   
  11.           
  12.         Dim connectionString As String = _  
  13.             "Driver={Microsoft Access Driver (*.mdb)};" _  
  14.            & "Dbq=c:\Data\Northwind.mdb;Uid=Admin;Pwd=;"  
  15.   
  16.          Dim queryString As String = _  
  17.             "SELECT ProductID, UnitPrice, ProductName from Products " _  
  18.             & "WHERE UnitPrice > ? " _  
  19.             & "ORDER BY UnitPrice DESC;"  
  20.   
  21.         Dim paramValue As Integer = 5  
  22.   
  23.          
  24.         Using connection As New OdbcConnection(connectionString)  
  25.   
  26.             Dim command As New OdbcCommand(queryString, connection)  
  27.             command.Parameters.AddWithValue("@pricePoint", paramValue)  
  28.   
  29.              
  30.             Try  
  31.                 connection.Open()  
  32.                 Dim dataReader As OdbcDataReader = _  
  33.                  command.ExecuteReader()  
  34.                 Do While dataReader.Read()  
  35.                     Console.WriteLine( _  
  36.                         vbTab & "{0}" & vbTab & "{1}" & vbTab & "{2}", _  
  37.                      dataReader(0), dataReader(1), dataReader(2))  
  38.                 Loop  
  39.                 dataReader.Close()  
  40.   
  41.             Catch ex As Exception  
  42.                 Console.WriteLine(ex.Message)  
  43.             End Try  
  44.             Console.ReadLine()  
  45.         End Using  
  46.     End Sub  
  47. End Class  
  48.   

DataSet

    DataSet是专门为独立于任何数据源的数据访问而设计的。因此,它可以用于多种不同的数据源,用于 XML 数据,或用于管理应用程序本地的数据。 DataSet 包含一个或多个 DataTable 对象的集合,这些对象由数据行和数据列以及有关 DataTable 对象中数据的主键、外键、约束和关系信息组成。

下图阐释了 .NET Framework 数据提供程序和 DataSet 之间的关系。


下面的示例由几种方法组成,这些方法互相结合,从Northwind 数据库中创建并填充DataSet

[plain] view plaincopy
  1. Option Explicit On  
  2. Option Strict On  
  3.   
  4. Imports System.Data  
  5. Imports system.Data.SqlClient  
  6.   
  7. Public Class NorthwindDataSet  
  8.   
  9.     Public Shared Sub Main()  
  10.         Dim connectionString As String = _  
  11.             GetConnectionString()  
  12.         ConnectToData(connectionString)  
  13.     End Sub  
  14.   
  15.     Private Shared Sub ConnectToData(ByVal connectionString As String)  
  16.   
  17.         Using connection As SqlConnection = New SqlConnection(connectionString)  
  18.   
  19.            Dim suppliersAdapter As SqlDataAdapter =New SqlDataAdapter()  
  20.   
  21.             suppliersAdapter.TableMappings.Add("Table", "Suppliers")  
  22.   
  23.             connection.Open()  
  24.             Console.WriteLine("The SqlConnection is open.")  
  25.   
  26.             Dim suppliersCommand As SqlCommand = New SqlCommand( "SELECT SupplierID, CompanyName FROM dbo.Suppliers;",connection)  
  27.             suppliersCommand.CommandType = CommandType.Text  
  28.   
  29.   
  30.             suppliersAdapter.SelectCommand = suppliersCommand  
  31.   
  32.             Dim dataSet As DataSet = New DataSet("Suppliers")  
  33.             suppliersAdapter.Fill(dataSet)  
  34.   
  35.             Dim productsAdapter As SqlDataAdapter = New SqlDataAdapter()  
  36.             productsAdapter.TableMappings.Add("Table", "Products")  
  37.   
  38.             Dim productsCommand As SqlCommand = New SqlCommand("SELECT ProductID, SupplierID FROM dbo.Products;"connection)  
  39.             productsAdapter.SelectCommand = productsCommand  
  40.   
  41.             productsAdapter.Fill(dataSet)  
  42.   
  43.             connection.Close()  
  44.             Console.WriteLine("The SqlConnection is closed.")  
  45.   
  46.   
  47.             Dim parentColumn As DataColumn = dataSet.Tables("Suppliers").Columns("SupplierID")  
  48.             Dim childColumn As DataColumn = dataSet.Tables("Products").Columns("SupplierID")  
  49.             Dim relation As DataRelation = New System.Data.DataRelation("SuppliersProducts",parentColumn, childColumn)  
  50.             dataSet.Relations.Add(relation)  
  51.   
  52.             Console.WriteLine("The {0} DataRelation has been created.", relation.RelationName)  
  53.         End Using  
  54.   
  55.     End Sub  
  56.   
  57.     Private Shared Function GetConnectionString() As String  
  58.   
  59.         Return "Data Source=(local);Initial Catalog=Northwind;" & "Integrated Security=SSPI;"  
  60.   
  61.     End Function  
  62. End Class  

选择 DataReader 或 DataSet


    在决定应用程序应使用 DataReader还是应使用 DataSet时,应考虑应用程序所需的功能类型。 使用 DataSet 可执行以下操作:

  • 在应用程序中将数据缓存在本地,以便可以对数据进行处理。 如果只需要读取查询结果,则 DataReader 是更好的选择。
  • 在层间或从 XML Web services 对数据进行远程处理。
  • 与数据进行动态交互,例如绑定到 Windows 窗体控件或组合并关联来自多个源的数据。
  • 对数据执行大量的处理,而不需要与数据源保持打开的连接,从而将该连接释放给其他客户端使用。

    如果不需要 DataSet 所提供的功能,则可以通过使用 DataReader 以只进、只读方式返回数据,从而提高应用程序的性能。 虽然DataAdapter 使用 DataReader 来填充DataSet 的内容,但使用 DataReader 可以提升性能,因为这样可以节省 DataSet 所使用的内存,并将省去创建 DataSet 并填充其内容所需的处理。

转载自:http://blog.csdn.net/zhang_xinxiu/article/details/8685424

阅读(1110) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~