進行檢索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 執行命令,并在控制臺窗口中顯示結果。
- 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