語言
本頁面上的程式碼清單示範如何使用下列 ADO.NET 技術來擷取資料庫中的資料:
ADO.NET 資料提供者:
SqlClient (
Microsoft.Data.SqlClient)OleDb (
System.Data.OleDb)Odbc (
System.Data.Odbc)OracleClient (
System.Data.OracleClient)
ADO.NET Entity Framework:
EntityClient (
System.Data.EntityClient)
ADO.NET 資料提供者範例
下列程式碼清單將示範如何使用 ADO.NET 資料提供者來擷取資料庫中的資料。 資料會傳入 DataReader 中。 如需詳細資訊,請參閱使用 DataReader擷取資料。
SqlClient
若要透過 ADO.NET 存取 SQL Server,請使用 Microsoft.Data.SqlClient NuGet 套件。 以下的 C# 與 Visual Basic 專案以 .NET 10 和 .NET Framework 4.8.1 為目標,並參考了此套件。 使用 .NET 10 SDK 來建立專案。
範例中查詢 Northwind 範例資料庫中的 dbo.Products 資料表。
SqlCommand 會選擇 UnitPrice 值大於 5 的產品。 該 SqlParameter 指定價格為 Money。
SqlDataReader 會依單位價格由高到低讀取產品 ID、單價和產品名稱。
using這些區塊(Using在 Visual Basic 中)會處置讀取器、指令和 SqlConnection。
在執行任一專案前,先在啟動範例的處理程序中設定 SQL_CONNECTION_STRING 環境變數。 例如,在整合驗證的 Windows 上,請使用以下 PowerShell 指令。 用你的伺服器名稱替換 <server>,並使用用戶端信任的憑證配置伺服器。
$env:SQL_CONNECTION_STRING = 'Server=<server>;Database=Northwind;Integrated Security=true;Encrypt=true;TrustServerCertificate=false'
關於其他認證選項,請參見 連線字串語法。
重要
Microsoft建議您使用可用的最安全驗證流程。 如果您正在連接 Azure SQL,建議使用的驗證方法為 Azure 資源受控識別。
若要使用驅動程式的 Microsoft Entra ID 認證模式,包括管理身份,也請安裝 Microsoft.Data.SqlClient.Extensions.Azure NuGet 套件。 關於設定說明,請參見 Microsoft Entra ID 認證。
using System;
using System.Data;
using Microsoft.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING")
?? throw new InvalidOperationException("Set the SQL_CONNECTION_STRING environment variable.");
const string queryString =
"SELECT ProductID, UnitPrice, ProductName FROM dbo.Products "
+ "WHERE UnitPrice > @pricePoint ORDER BY UnitPrice DESC;";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.Parameters.Add("@pricePoint", SqlDbType.Money).Value = 5m;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"{reader.GetInt32(0)}\t{reader.GetDecimal(1)}\t{reader.GetString(2)}");
}
}
}
}
}
Option Explicit On
Option Strict On
Imports System
Imports System.Data
Imports Microsoft.Data.SqlClient
Module Program
Sub Main()
Dim connectionString As String = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING")
If String.IsNullOrWhiteSpace(connectionString) Then
Throw New InvalidOperationException("Set the SQL_CONNECTION_STRING environment variable.")
End If
Const queryString As String =
"SELECT ProductID, UnitPrice, ProductName FROM dbo.Products " &
"WHERE UnitPrice > @pricePoint ORDER BY UnitPrice DESC;"
Using connection As New SqlConnection(connectionString),
command As New SqlCommand(queryString, connection)
command.Parameters.Add("@pricePoint", SqlDbType.Money).Value = 5D
connection.Open()
Using reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine($"{reader.GetInt32(0)}{vbTab}{reader.GetDecimal(1)}{vbTab}{reader.GetString(2)}")
End While
End Using
End Using
End Sub
End Module
從任一片段專案目錄中執行 dotnet run --framework net10.0。 在安裝 .NET Framework 4.8.1 的 Windows 上,請使用 dotnet run --framework net481.
OleDb
這則範例中的程式碼會假設您可以連接至 Microsoft Access Northwind 範例資料庫。 這段程式碼會建立 OleDbCommand,以便從 Products 資料表中選取資料列,並且加入 OleDbParameter,以便將結果限制為 UnitPrice 大於指定之參數值 (在此案例中為 5) 的資料列。
OleDbConnection 是在 using 區塊內部開啟,可確保當程式碼結束時,資源會被關閉和釋放。 然後,程式碼會使用 OleDbDataReader 來執行此命令,並且在主控台視窗中顯示結果。
using System;
using System.Data.OleDb;
using System.Runtime.Versioning;
// API is only supported on Windows
[SupportedOSPlatform("windows")]
static class Program
{
static void Main()
{
const string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "c:\\Data\\Northwind.mdb;...";
// Provide the query string with a parameter placeholder.
const string queryString =
"SELECT ProductID, UnitPrice, ProductName from products "
+ "WHERE UnitPrice > ? "
+ "ORDER BY UnitPrice DESC;";
// Specify the parameter value.
const int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (OleDbConnection connection =
new(connectionString))
{
// Create the Command and Parameter objects.
OleDbCommand command = new(queryString, connection);
command.Parameters.AddWithValue("@pricePoint", paramValue);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"\t{reader[0]}\t{reader[1]}\t{reader[2]}");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
Option Explicit On
Option Strict On
Imports System.Data.OleDb
Imports System.Runtime.Versioning
Public Class Program
<SupportedOSPlatform("Windows")>
Public Shared Sub Main()
' The connection string assumes that the Access
' Northwind.mdb is located in the c:\Data folder.
Dim connectionString As String = "..."
' Provide the query string with a parameter placeholder.
Dim queryString As String =
"SELECT ProductID, UnitPrice, ProductName from Products " _
& "WHERE UnitPrice > ? " _
& "ORDER BY UnitPrice DESC;"
' Specify the parameter value.
Dim paramValue As Integer = 5
' Create and open the connection in a using block. This
' ensures that all resources will be closed and disposed
' when the code exits.
Using connection As New OleDbConnection(connectionString)
' Create the Command and Parameter objects.
Dim command As New OleDbCommand(queryString, connection)
command.Parameters.AddWithValue("@pricePoint", paramValue)
' Open the connection in a try/catch block.
' Create and execute the DataReader, writing the result
' set to the console window.
Try
connection.Open()
Dim dataReader As OleDbDataReader =
command.ExecuteReader()
Do While dataReader.Read()
Console.WriteLine(
vbTab & "{0}" & vbTab & "{1}" & vbTab & "{2}",
dataReader(0), dataReader(1), dataReader(2))
Loop
dataReader.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Using
End Sub
End Class
ODBC(開放式資料庫連線)
這則範例中的程式碼會假設您可以連接至 Microsoft Access Northwind 範例資料庫。 這段程式碼會建立 OdbcCommand,以便從 Products 資料表中選取資料列,並且加入 OdbcParameter,以便將結果限制為 UnitPrice 大於指定之參數值 (在此案例中為 5) 的資料列。
OdbcConnection 是在 using 區塊內部開啟,可確保程式碼結束時,系統會關閉和處置資源。 然後,程式碼會使用 OdbcDataReader 來執行此命令,並且在主控台視窗中顯示結果。
using System;
using System.Data.Odbc;
static class Program
{
static void Main()
{
const string connectionString =
"Driver={Microsoft Access Driver (*.mdb)};...";
// Provide the query string with a parameter placeholder.
const string queryString =
"SELECT ProductID, UnitPrice, ProductName from products "
+ "WHERE UnitPrice > ? "
+ "ORDER BY UnitPrice DESC;";
// Specify the parameter value.
const int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (OdbcConnection connection =
new(connectionString))
{
// Create the Command and Parameter objects.
OdbcCommand command = new(queryString, connection);
command.Parameters.AddWithValue("@pricePoint", paramValue);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"\t{reader[0]}\t{reader[1]}\t{reader[2]}");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
Option Explicit On
Option Strict On
Imports System.Data.Odbc
Public Class Program
Public Shared Sub Main()
' The connection string assumes that the Access
' Northwind.mdb is located in the c:\Data folder.
Dim connectionString As String = "..."
' Provide the query string with a parameter placeholder.
Dim queryString As String =
"SELECT ProductID, UnitPrice, ProductName from Products " _
& "WHERE UnitPrice > ? " _
& "ORDER BY UnitPrice DESC;"
' Specify the parameter value.
Dim paramValue As Integer = 5
' Create and open the connection in a using block. This
' ensures that all resources will be closed and disposed
' when the code exits.
Using connection As New OdbcConnection(connectionString)
' Create the Command and Parameter objects.
Dim command As New OdbcCommand(queryString, connection)
command.Parameters.AddWithValue("@pricePoint", paramValue)
' Open the connection in a try/catch block.
' Create and execute the DataReader, writing the result
' set to the console window.
Try
connection.Open()
Dim dataReader As OdbcDataReader =
command.ExecuteReader()
Do While dataReader.Read()
Console.WriteLine(
vbTab & "{0}" & vbTab & "{1}" & vbTab & "{2}",
dataReader(0), dataReader(1), dataReader(2))
Loop
dataReader.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Using
End Sub
End Class
Oracle用戶端
這則範例中的程式碼會假設您已連接到 Oracle 伺服器上的 DEMO.CUSTOMER。 您也必須加入 System.Data.OracleClient.dll 的參考。 此程式碼會將資料傳入 OracleDataReader 中。
重要
Microsoft建議您使用可用的最安全驗證流程。 如果您正在連接 Azure SQL,建議使用的驗證方法為 Azure 資源受控識別。
using System;
using System.Data.OracleClient;
static class Program
{
static void Main()
{
const string connectionString =
"Data Source=ThisOracleServer;Integrated Security=yes;";
const string queryString =
"SELECT CUSTOMER_ID, NAME FROM DEMO.CUSTOMER";
using (OracleConnection connection =
new(connectionString))
{
OracleCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"\t{reader[0]}\t{reader[1]}");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Option Explicit On
Option Strict On
Imports Oracle.ManagedDataAccess.Client
Public Class Program
Public Shared Sub Main()
Dim connectionString As String =
"..."
Dim queryString As String =
"SELECT CUSTOMER_ID, NAME FROM DEMO.CUSTOMER"
Using connection As New OracleConnection(connectionString)
Dim command As OracleCommand = connection.CreateCommand()
command.CommandText = queryString
Try
connection.Open()
Dim dataReader As OracleDataReader =
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
End Class
Entity Framework 範例
下列程式碼清單將示範如何透過查詢 Entity Data Model (EDM) 中的實體,擷取資料來源中的資料。 這些範例會使用以 Northwind 範例資料庫為基礎的模型。 如需 Entity Framework 的詳細資訊,請參閱 Entity Framework 概觀。
LINQ to Entities
這則範例中的程式碼會使用 LINQ 查詢來傳回資料當做 Categories 物件,而這些物件會投影成僅包含 CategoryID 和 CategoryName 屬性的匿名型別。 如需詳細資訊,請參閱 LINQ to Entities 概觀。
using System;
using System.Linq;
using System.Data.Objects;
using NorthwindModel;
class LinqSample
{
public static void ExecuteQuery()
{
using (NorthwindEntities context = new NorthwindEntities())
{
try
{
var query = from category in context.Categories
select new
{
categoryID = category.CategoryID,
categoryName = category.CategoryName
};
foreach (var categoryInfo in query)
{
Console.WriteLine("\t{0}\t{1}",
categoryInfo.categoryID, categoryInfo.categoryName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Option Explicit On
Option Strict On
Imports System.Linq
Imports System.Data.Objects
Imports NorthwindModel
Class LinqSample
Public Shared Sub ExecuteQuery()
Using context As NorthwindEntities = New NorthwindEntities()
Try
Dim query = From category In context.Categories _
Select New With _
{ _
.categoryID = category.CategoryID, _
.categoryName = category.CategoryName _
}
For Each categoryInfo In query
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _
categoryInfo.categoryID, categoryInfo.categoryName)
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Sub
End Class
類型化的 ObjectQuery
這則範例中的程式碼會使用 ObjectQuery<T> 來傳回資料當做 Categories 物件。 如需詳細資訊,請參閱物件查詢。
using System;
using System.Data.Objects;
using NorthwindModel;
class ObjectQuerySample
{
public static void ExecuteQuery()
{
using (NorthwindEntities context = new NorthwindEntities())
{
ObjectQuery<Categories> categoryQuery = context.Categories;
foreach (Categories category in
categoryQuery.Execute(MergeOption.AppendOnly))
{
Console.WriteLine("\t{0}\t{1}",
category.CategoryID, category.CategoryName);
}
}
}
}
Option Explicit On
Option Strict On
Imports System.Data.Objects
Imports NorthwindModel
Class ObjectQuerySample
Public Shared Sub ExecuteQuery()
Using context As NorthwindEntities = New NorthwindEntities()
Dim categoryQuery As ObjectQuery(Of Categories) = context.Categories
For Each category As Categories In _
categoryQuery.Execute(MergeOption.AppendOnly)
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _
category.CategoryID, category.CategoryName)
Next
End Using
End Sub
End Class
EntityClient
這則範例中的程式碼會使用 EntityCommand 來執行 Entity SQL 查詢。 此查詢會傳回一個包含代表「類別」實體類型的記錄之清單。 EntityDataReader 可用於存取結果集中的資料記錄。 如需詳細資訊,請參閱 EntityClient 提供者的 Entity Framework。
using System;
using System.Data;
using System.Data.Common;
using System.Data.EntityClient;
using NorthwindModel;
class EntityClientSample
{
public static void ExecuteQuery()
{
string queryString =
@"SELECT c.CategoryID, c.CategoryName
FROM NorthwindEntities.Categories AS c";
using (EntityConnection conn =
new EntityConnection("name=NorthwindEntities"))
{
try
{
conn.Open();
using (EntityCommand query = new EntityCommand(queryString, conn))
{
using (DbDataReader rdr =
query.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (rdr.Read())
{
Console.WriteLine("\t{0}\t{1}", rdr[0], rdr[1]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Option Explicit On
Option Strict On
Imports System.Data
Imports System.Data.Common
Imports System.Data.EntityClient
Imports NorthwindModel
Class EntityClientSample
Public Shared Sub ExecuteQuery()
Dim queryString As String = _
"SELECT c.CategoryID, c.CategoryName " & _
"FROM NorthwindEntities.Categories AS c"
Using conn As EntityConnection = _
New EntityConnection("name=NorthwindEntities")
Try
conn.Open()
Using query As EntityCommand = _
New EntityCommand(queryString, conn)
Using rdr As DbDataReader = _
query.ExecuteReader(CommandBehavior.SequentialAccess)
While rdr.Read()
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _
rdr(0), rdr(1))
End While
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Sub
End Class
LINQ to SQL
這則範例中的程式碼會使用 LINQ 查詢來傳回資料當做 Categories 物件,而這些物件會投影成僅包含 CategoryID 和 CategoryName 屬性的匿名型別。 這則範例是以 Northwind 資料內容為基礎。 如需詳細資訊,請參閱使用者入門。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Northwind;
class LinqSqlSample
{
public static void ExecuteQuery()
{
using (NorthwindDataContext db = new NorthwindDataContext())
{
try
{
var query = from category in db.Categories
select new
{
categoryID = category.CategoryID,
categoryName = category.CategoryName
};
foreach (var categoryInfo in query)
{
Console.WriteLine("vbTab {0} vbTab {1}",
categoryInfo.categoryID, categoryInfo.categoryName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Option Explicit On
Option Strict On
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Northwind
Class LinqSqlSample
Public Shared Sub ExecuteQuery()
Using db As NorthwindDataContext = New NorthwindDataContext()
Try
Dim query = From category In db.Categories _
Select New With _
{ _
.categoryID = category.CategoryID, _
.categoryName = category.CategoryName _
}
For Each categoryInfo In query
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _
categoryInfo.categoryID, categoryInfo.categoryName)
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Sub
End Class