příklady kódu ADO.NET
Výpisy kódu na této stránce ukazují, jak načíst data z databáze pomocí následujících technologií ADO.NET:
ADO.NET zprostředkovatelů dat:
SqlClient (
System.Data.SqlClient
)OleDb (
System.Data.OleDb
)Odbc (
System.Data.Odbc
)OracleClient (
System.Data.OracleClient
)
ADO.NET Entity Framework:
EntityClient (
System.Data.EntityClient
)
Příklady poskytovatele dat ADO.NET
Následující výpisy kódu ukazují, jak načíst data z databáze pomocí ADO.NET zprostředkovatelů dat. Data jsou vrácena v .DataReader
Další informace naleznete v tématu Načítání dat pomocí třídy DataReader.
SqlClient
Kód v tomto příkladu předpokládá, že se můžete připojit k Northwind
ukázkové databázi na Microsoft SQL Serveru. Kód vytvoří řádek SqlCommand pro výběr řádků z tabulky Products a přidá hodnotu, která SqlParameter omezí výsledky na řádky s hodnotou UnitPrice větší než zadaná hodnota parametru, v tomto případě 5. Otevře SqlConnection se uvnitř using
bloku, který zajistí, že se prostředky zavřou a odstraní, když se kód ukončí. Kód spustí příkaz pomocí znaku a SqlDataReaderzobrazí výsledky v okně konzoly. Pokud používáte System.Data.SqlClient
, měli byste zvážit upgrade na místo, kde Microsoft.Data.SqlClient
se provádějí budoucí investice a vývoj nových funkcí. Další informace naleznete v tématu Představujeme nový Microsoft.Data.SqlClient.
Důležité
Microsoft doporučuje používat nejbezpečnější dostupný tok ověřování. Pokud se připojujete k Azure SQL, spravované identity pro prostředky Azure se doporučují metodou ověřování.
using System;
using System.Data.SqlClient;
static class Program
{
static void Main()
{
const string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
const string queryString =
"SELECT ProductID, UnitPrice, ProductName from dbo.products "
+ "WHERE UnitPrice > @pricePoint "
+ "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 (SqlConnection connection =
new(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand 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();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
Option Explicit On
Option Strict On
Imports System.Data
Imports System.Data.SqlClient
Public Class Program
Public Shared Sub Main()
Dim connectionString As String = _
"..."
' Provide the query string with a parameter placeholder.
Dim queryString As String = _
"SELECT ProductID, UnitPrice, ProductName from dbo.Products " _
& "WHERE UnitPrice > @pricePoint " _
& "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 SqlConnection(connectionString)
' Create the Command and Parameter objects.
Dim command As New SqlCommand(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 SqlDataReader = _
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
OleDb
Kód v tomto příkladu předpokládá, že se můžete připojit k ukázkové databázi Microsoft Access Northwind. Kód vytvoří řádek OleDbCommand pro výběr řádků z tabulky Products a přidá hodnotu, která OleDbParameter omezí výsledky na řádky s hodnotou UnitPrice větší než zadaná hodnota parametru, v tomto případě 5. Otevře OleDbConnection se uvnitř using
bloku, který zajistí, že se prostředky zavřou a odstraní, když se kód ukončí. Kód spustí příkaz pomocí znaku a OleDbDataReaderzobrazí výsledky v okně konzoly.
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{0}\t{1}\t{2}",
reader[0], reader[1], 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
Kód v tomto příkladu předpokládá, že se můžete připojit k ukázkové databázi Microsoft Access Northwind. Kód vytvoří řádek OdbcCommand pro výběr řádků z tabulky Products a přidá hodnotu, která OdbcParameter omezí výsledky na řádky s hodnotou UnitPrice větší než zadaná hodnota parametru, v tomto případě 5. Otevře OdbcConnection se uvnitř using
bloku, který zajistí, že se prostředky zavřou a odstraní, když se kód ukončí. Kód spustí příkaz pomocí znaku a OdbcDataReaderzobrazí výsledky v okně konzoly.
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{0}\t{1}\t{2}",
reader[0], reader[1], 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
OracleClient
Kód v tomto příkladu předpokládá připojení k DEMO. CUSTOMER na serveru Oracle. Musíte také přidat odkaz na System.Data.OracleClient.dll. Kód vrátí data v objektu OracleDataReader.
Důležité
Microsoft doporučuje používat nejbezpečnější dostupný tok ověřování. Pokud se připojujete k Azure SQL, spravované identity pro prostředky Azure se doporučují metodou ověřování.
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{0}\t{1}",
reader[0], 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
Příklady Entity Frameworku
Následující výpisy kódu ukazují, jak načíst data ze zdroje dat dotazováním entit v modelu Entity Data Model (EDM). Tyto příklady používají model založený na ukázkové databázi Northwind. Další informace o Entity Framework naleznete v tématu Entity Framework Přehled.
LINQ to Entities
Kód v tomto příkladu používá dotaz LINQ k vrácení dat jako categories objekty, které jsou projektovány jako anonymní typ, který obsahuje pouze CategoryID a CategoryName vlastnosti. Další informace naleznete v tématu LINQ to Entities Overview.
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
Typed ObjectQuery
Kód v tomto příkladu ObjectQuery<T> používá k vrácení dat jako objektů Categories. Další informace naleznete v tématu Dotazy na objekty.
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
Kód v tomto příkladu EntityCommand používá k provedení dotazu Entity SQL. Tento dotaz vrátí seznam záznamů, které představují instance typu entity Categories. Slouží EntityDataReader k přístupu k datovým záznamům v sadě výsledků. Další informace naleznete v tématu EntityClient Provider for the 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
Technologie LINQ to SQL
Kód v tomto příkladu používá dotaz LINQ k vrácení dat jako categories objekty, které jsou projektovány jako anonymní typ, který obsahuje pouze CategoryID a CategoryName vlastnosti. Tento příklad je založený na kontextu dat Northwind. Další informace naleznete v tématu Začínáme.
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