进行检索ADO.NET 数据说明

以下代码列表演示如何使用 ADO.NET 数据提供程序从数据库中检索数据。数据在一个 DataReader 中返回。有关更多信息,请参见使用 DataReader 检索数据 (ADO.NET)。

SqlClient
此示例中的代码假定您可以连接到 Microsoft SQL Server 7.0 或更高版本上的 Northwind 示例数据库。ADO.NET 数据在此情形 5 中,示例代码创建一个 SqlCommand 以从 Products 表中选择行,并添加 SqlParameter 来将结果限制为其 UnitPrice 大于指定参数值的行。

SqlConnection 在 using 块内打开,这将确保在代码退出时会关闭和释放资源。示例代码使用 SqlDataReader 执行命令,ADO.NET 数据并在控制台窗口中显示结果。此示例中的代码假定您可以连接到 Microsoft Access Northwind 示例数据库。#t#

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

 
 
  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 = GetConnectionString()  
  12. Dim queryString As String = _ 
  13.  "SELECT CategoryID, CategoryName FROM dbo.Categories;"  
  14.  
  15. Using connection As New SqlConnection(connectionString)  
  16. Dim command As SqlCommand = connection.CreateCommand()  
  17. command.CommandText = queryString 
  18. Try  
  19. connection.Open()  
  20. Dim dataReader As SqlDataReader = _ 
  21.  command.ExecuteReader()  
  22. Do While dataReader.Read()  
  23. Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _  
  24.  dataReader(0), dataReader(1))  
  25. Loop  
  26. dataReader.Close()  
  27.  
  28. Catch ex As Exception  
  29. Console.WriteLine(ex.Message)  
  30. End Try  
  31. End Using  
  32. End Sub  
  33.  
  34. Private Shared Function GetConnectionString() As String  
  35. ' To avoid storing the connection string in your code,  
  36. ' you can retrieve it from a configuration file.  
  37. Return "Data Source=(local);Initial Catalog=Northwind;" _  
  38.  & "Integrated Security=SSPI;"  
  39. End Function  
  40. End Class 
THE END