Nyelv

ADO.NET példakódokra

Az ezen az oldalon található kódlisták bemutatják, hogyan kérhetők le adatok az adatbázisból az alábbi ADO.NET technológiák használatával:

ADO.NET adatszolgáltatói példák

Az alábbi kódrészletek bemutatják, hogyan lehet adatokat lekérni egy adatbázisból ADO.NET adatszolgáltatók használatával. Az adatok visszaadásra kerülnek egy DataReader-ban. További információ: Adatok beolvasása DataReader használatával.

SqlClient

Az SQL Server ADO.NET-tel való eléréséhez használja a Microsoft.Data.SqlClient NuGet-csomagot. A következő C# és Visual Basic projektek .NET 10-et és .NET Framework 4.8.1-et céloznak meg, és hivatkoznak erre a csomagra. A projektek fordításához használja a .NET 10 SDK-t.

A példák lekérdezik a dbo.Products táblát a Northwind mintaadatbázisban. Az SqlCommand azokat a termékeket választja ki, amelyeknél a(z) UnitPrice nagyobb mint 5. A SqlParameter adja meg az árat: Money. A SqlDataReader rendszer a termékazonosítót, az egységárat és a terméknevet az egységár csökkenő sorrendjében olvassa. A using blokkok (Using a Visual Basicben) felszabadítják az olvasót, a parancsot és a SqlConnectionkapcsolatot.

Mielőtt bármelyik projektet futtatja, állítsa be a SQL_CONNECTION_STRING környezeti változót a példát elindító folyamatban. Például Windows rendszeren integrált hitelesítéssel használja a következő PowerShell-parancsot. Cserélje le a(z) <server> elemet a kiszolgáló nevére, és konfigurálja a kiszolgálót egy olyan tanúsítvánnyal, amelyben az ügyfél megbízik.

$env:SQL_CONNECTION_STRING = 'Server=<server>;Database=Northwind;Integrated Security=true;Encrypt=true;TrustServerCertificate=false'

Egyéb hitelesítési lehetőségekért tekintse meg a Kapcsolati sztring szintaxisát.

Fontos

A Microsoft azt javasolja, hogy a legbiztonságosabb hitelesítési folyamatot használja. Az Azure SQL-hez csatlakozáskor a Felügyelt identitások az Azure-erőforrásokhoz az ajánlott hitelesítési módszer.

Az illesztőprogram Microsoft Entra ID hitelesítési módjainak (beleértve a felügyelt identitást is) használatához telepítse a Microsoft.Data.SqlClient.Extensions.Azure NuGet-csomagot is. A beállítási utasításokért lásd Microsoft Entra ID hitelesítést.

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

Bármelyik kódrészlet projektkönyvtárából futtassa a következőt: dotnet run --framework net10.0 Windows rendszeren, amelyen telepítve van a .NET Framework 4.8.1, használja a dotnet run --framework net481 elemet.

OleDb

A példában szereplő kód feltételezi, hogy csatlakozhat a Microsoft Access Northwind mintaadatbázisához. A kód létrehoz egy OleDbCommand sort a Termékek táblából való kiválasztásához, és hozzáad egy OleDbParameter olyan értéket, amely a megadott paraméterértéknél nagyobb UnitPrice értékkel rendelkező sorokra korlátozza az eredményeket, ebben az esetben 5. A OleDbConnection egy using blokkon belül nyílik meg, amely biztosítja, hogy az erőforrások lezárásra és ártalmatlanításra kerülnek, amikor a kód kilép. A kód egy paranccsal hajtja végre a parancsot OleDbDataReader, és megjeleníti az eredményeket a konzolablakban.

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

A példában szereplő kód feltételezi, hogy csatlakozhat a Microsoft Access Northwind mintaadatbázisához. A kód létrehoz egy OdbcCommand sort a Termékek táblából való kiválasztásához, és hozzáad egy OdbcParameter olyan értéket, amely a megadott paraméterértéknél nagyobb UnitPrice értékkel rendelkező sorokra korlátozza az eredményeket, ebben az esetben 5. A OdbcConnection rendszer egy using blokkon belül nyílik meg, amely biztosítja az erőforrások bezárását és ártalmatlanítását a kód kilépésekor. A kód egy paranccsal hajtja végre a parancsot OdbcDataReader, és megjeleníti az eredményeket a konzolablakban.

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

OracleClient

A példában szereplő kód feltételezi, hogy csatlakozás történt a DEMO.CUSTOMER-hez egy Oracle kiszolgálón. A System.Data.OracleClient.dll-re is hivatkozást kell felvennie. A kód visszaadja az adatokat egy OracleDataReader.

Fontos

A Microsoft azt javasolja, hogy a legbiztonságosabb hitelesítési folyamatot használja. Az Azure SQL-hez csatlakozáskor a Felügyelt identitások az Azure-erőforrásokhoz az ajánlott hitelesítési módszer.

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

Entitás-keretrendszerre vonatkozó példák

Az alábbi kódrészletek bemutatják, hogyan lehet adatokat lekérni egy adatforrásból egy entitás adatmodellben (EDM) lévő entitások lekérdezésével. Ezek a példák a Northwind mintaadatbázison alapuló modellt használnak. Az Entity Frameworkről további információt az Entity Framework áttekintésében talál.

LINQ to Entities

A példában szereplő kód LINQ-lekérdezéssel adja vissza az adatokat Kategóriák objektumként, amelyek névtelen típusként vannak kivetítve, amely csak a CategoryID és a CategoryName tulajdonságokat tartalmazza. További információ: 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

Gépelt ObjectQuery

Az ebben a példában szereplő kód egy ObjectQuery<T> segítségével ad vissza adatokat "Kategóriák" objektumokként. További információ: Objektum-lekérdezések.

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

A példában szereplő kód egy EntityCommand Entity SQL-lekérdezés végrehajtására szolgál. Ez a lekérdezés a Kategóriák entitástípus példányait képviselő rekordok listáját adja vissza. Egy EntityDataReader az eredményhalmaz adatrekordjainak elérésére szolgál. További információ: EntityClient szolgáltató az Entity Framework számára.

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

A példában szereplő kód LINQ-lekérdezéssel adja vissza az adatokat Kategóriák objektumként, amelyek névtelen típusként vannak kivetítve, amely csak a CategoryID és a CategoryName tulajdonságokat tartalmazza. Ez a példa a Northwind-adatkörnyezeten alapul. További információ: Első lépések.

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

Lásd még