进行检索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 示例数据库.
    在此情形 5 中,示例代码创建一个ADO.NET 数据 OleDbCommand 以从 Products 表中选择行,并添加 OleDbParameter 来将结果限制为其 UnitPrice 大于指定参数值的行.OleDbConnection 在 using 块内打开,这将确保在代码退出时会关闭和释放资源.示例代码使用 OleDbDataReader 执行命令,并在控制台窗口中显示结果.
    Option Explicit On
    Option Strict On
    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    Public Class Program
    Public Shared Sub Main()
    Dim connectionString As String = GetConnectionString()
    Dim queryString As String = _  “SELECT CategoryID, CategoryName FROM dbo.Categories;”
    Using connection As New SqlConnection(connectionString)
    Dim command As SqlCommand = connection.CreateCommand()
    command.CommandText = queryString Try
    connection.Open()
    Dim dataReader As SqlDataReader = _  command.ExecuteReader()
    Do While dataReader.Read()
    Console.WriteLine(vbTab & “{0}” & vbTab & “{1}”, _   dataReader(0), dataReader(1))
    Loop
    dataReader.Close()
    Catch ex As Exception
    Console.WriteLine(ex.Message)
    End Try
    End Using
    End Sub
    Private Shared Function GetConnectionString() As String
    ' To avoid storing the connection string in your code,
    ' you can retrieve it from a configuration file.
    Return “Data Source=(local);Initial Catalog=Northwind;” _   & “Integrated Security=SSPI;”
    End Function
    End Class