進(jìn)行檢索ADO.NET 數(shù)據(jù)說明
以下代碼列表演示如何使用 ADO.NET 數(shù)據(jù)提供程序從數(shù)據(jù)庫中檢索數(shù)據(jù)。數(shù)據(jù)在一個 DataReader 中返回。有關(guān)更多信息,請參見使用 DataReader 檢索數(shù)據(jù) (ADO.NET)。
SqlClient
此示例中的代碼假定您可以連接到 Microsoft SQL Server 7.0 或更高版本上的 Northwind 示例數(shù)據(jù)庫。ADO.NET 數(shù)據(jù)在此情形 5 中,示例代碼創(chuàng)建一個 SqlCommand 以從 Products 表中選擇行,并添加 SqlParameter 來將結(jié)果限制為其 UnitPrice 大于指定參數(shù)值的行。
SqlConnection 在 using 塊內(nèi)打開,這將確保在代碼退出時會關(guān)閉和釋放資源。示例代碼使用 SqlDataReader 執(zhí)行命令,ADO.NET 數(shù)據(jù)并在控制臺窗口中顯示結(jié)果。此示例中的代碼假定您可以連接到 Microsoft Access Northwind 示例數(shù)據(jù)庫。#t#
在此情形 5 中,示例代碼創(chuàng)建一個ADO.NET 數(shù)據(jù) OleDbCommand 以從 Products 表中選擇行,并添加 OleDbParameter 來將結(jié)果限制為其 UnitPrice 大于指定參數(shù)值的行。OleDbConnection 在 using 塊內(nèi)打開,這將確保在代碼退出時會關(guān)閉和釋放資源。示例代碼使用 OleDbDataReader 執(zhí)行命令,并在控制臺窗口中顯示結(jié)果。
- 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