Langue

Modification de données avec dbDataAdapter

La méthode CreateDataAdapter d'un objet DbProviderFactory produit un objet DbDataAdapter fortement typé pour le fournisseur de données sous-jacent spécifié lors de la création de la fabrique. Vous pouvez ensuite utiliser un DbCommandBuilder pour créer des commandes afin d'insérer, de mettre à jour et de supprimer des données d'un DataSet vers une source de données.

Récupération de données avec dbDataAdapter

Cet exemple montre comment créer un type fortement typé DbDataAdapter en fonction d’un nom de fournisseur et d’une chaîne de connexion. Le code utilise la méthode CreateConnection de DbProviderFactory pour créer un DbConnection. Ensuite, le code utilise la méthode CreateCommand pour créer un DbCommand afin de sélectionner des données en définissant ses propriétés CommandText et Connection. Enfin, le code crée un DbDataAdapter objet à l’aide de la CreateDataAdapter méthode et définit sa SelectCommand propriété. La méthode Fill du DbDataAdapter charge les données dans un DataTable.

static void CreateDataAdapter(string providerName, string connectionString)
{
    try
    {
        // Create the DbProviderFactory and DbConnection.
        DbProviderFactory factory =
            DbProviderFactories.GetFactory(providerName);

        DbConnection connection = factory.CreateConnection();
        connection.ConnectionString = connectionString;

        using (connection)
        {
            // Define the query.
            const string queryString =
                "SELECT CategoryName FROM Categories";

            // Create the DbCommand.
            DbCommand command = factory.CreateCommand();
            command.CommandText = queryString;
            command.Connection = connection;

            // Create the DbDataAdapter.
            DbDataAdapter adapter = factory.CreateDataAdapter();
            adapter.SelectCommand = command;

            // Fill the DataTable.
            DataTable table = new();
            adapter.Fill(table);

            //  Display each row and column value.
            foreach (DataRow row in table.Rows)
            {
                foreach (DataColumn column in table.Columns)
                {
                    Console.WriteLine(row[column]);
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
    Shared Sub CreateDataAdapter(ByVal providerName As String, _
        ByVal connectionString As String)

        ' Create the DbProviderFactory and DbConnection.
        Try
#If NET Then
            DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance)
#End If
            Dim factory As DbProviderFactory = _
               DbProviderFactories.GetFactory(providerName)

            Dim connection As DbConnection = _
                factory.CreateConnection()
            connection.ConnectionString = connectionString
            Using connection

                ' Define the query.
                Dim queryString As String = _
                  "SELECT CategoryName FROM Categories"

                'Create the DbCommand.
                Dim command As DbCommand = _
                    factory.CreateCommand()
                command.CommandText = queryString
                command.Connection = connection

                ' Create the DbDataAdapter.
                Dim adapter As DbDataAdapter = _
                    factory.CreateDataAdapter()
                adapter.SelectCommand = command

                ' Fill the DataTable
                Dim table As New DataTable
                adapter.Fill(table)

                'Display each row and column value.
                Dim row As DataRow
                Dim column As DataColumn
                For Each row In table.Rows
                    For Each column In table.Columns
                        Console.WriteLine(row(column))
                    Next
                Next
            End Using

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

Modification de données avec dbDataAdapter

Cet exemple montre comment modifier les données dans un DataTable en utilisant un DbDataAdapter et un DbCommandBuilder pour générer les commandes requises afin de mettre à jour les données à la source de données. La propriété SelectCommand du DbDataAdapter est définie de manière à récupérer le CustomerID et le CompanyName dans la table Customers. La GetInsertCommand méthode est utilisée pour définir la InsertCommand propriété, la GetUpdateCommand méthode est utilisée pour définir la UpdateCommand propriété et la GetDeleteCommand méthode est utilisée pour définir la DeleteCommand propriété. Le code ajoute une nouvelle ligne à la table Customers et met à jour la source de données. Le code localise ensuite la ligne ajoutée en recherchant sur customerID, qui est la clé primaire définie pour la table Customers. Il modifie CompanyName et met à jour la source de données. Enfin, le code supprime la ligne.

static void CreateDataAdapter(string providerName, string connectionString)
{
    try
    {
        // Create the DbProviderFactory and DbConnection.
        DbProviderFactory factory =
            DbProviderFactories.GetFactory(providerName);

        DbConnection connection = factory.CreateConnection();
        connection.ConnectionString = connectionString;

        using (connection)
        {
            // Define the query.
            const string queryString =
                "SELECT CustomerID, CompanyName FROM Customers";

            // Create the select command.
            DbCommand command = factory.CreateCommand();
            command.CommandText = queryString;
            command.Connection = connection;

            // Create the DbDataAdapter.
            DbDataAdapter adapter = factory.CreateDataAdapter();
            adapter.SelectCommand = command;

            // Create the DbCommandBuilder.
            DbCommandBuilder builder = factory.CreateCommandBuilder();
            builder.DataAdapter = adapter;

            // Get the insert, update and delete commands.
            adapter.InsertCommand = builder.GetInsertCommand();
            adapter.UpdateCommand = builder.GetUpdateCommand();
            adapter.DeleteCommand = builder.GetDeleteCommand();

            // Display the CommandText for each command.
            Console.WriteLine($"InsertCommand: {adapter.InsertCommand.CommandText}");
            Console.WriteLine($"UpdateCommand: {adapter.UpdateCommand.CommandText}");
            Console.WriteLine($"DeleteCommand: {adapter.DeleteCommand.CommandText}");

            // Fill the DataTable.
            DataTable table = new();
            adapter.Fill(table);

            // Insert a new row.
            DataRow newRow = table.NewRow();
            newRow["CustomerID"] = "XYZZZ";
            newRow["CompanyName"] = "XYZ Company";
            table.Rows.Add(newRow);

            adapter.Update(table);

            // Display rows after insert.
            Console.WriteLine();
            Console.WriteLine("----List All Rows-----");
            foreach (DataRow row in table.Rows)
            {
                Console.WriteLine($"{row[0]} {row[1]}");
            }
            Console.WriteLine("----After Insert-----");

            // Edit an existing row.
            DataRow[] editRow = table.Select("CustomerID = 'XYZZZ'");
            editRow[0]["CompanyName"] = "XYZ Corporation";

            adapter.Update(table);

            // Display rows after update.
            Console.WriteLine();
            foreach (DataRow row in table.Rows)
            {
                Console.WriteLine($"{row[0]} {row[1]}");
            }
            Console.WriteLine("----After Update-----");

            // Delete a row.
            DataRow[] deleteRow = table.Select("CustomerID = 'XYZZZ'");
            foreach (DataRow row in deleteRow)
            {
                row.Delete();
            }

            adapter.Update(table);

            // Display rows after delete.
            Console.WriteLine();
            foreach (DataRow row in table.Rows)
            {
                Console.WriteLine($"{row[0]} {row[1]}");
            }
            Console.WriteLine("----After Delete-----");
            Console.WriteLine("Customer XYZZZ was deleted.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
    Shared Sub CreateDataAdapter(ByVal providerName As String, _
        ByVal connectionString As String)

        ' Create the DbProviderFactory and DbConnection.
        Try
#If NET Then
            DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance)
#End If
            Dim factory As DbProviderFactory = _
               DbProviderFactories.GetFactory(providerName)

            Dim connection As DbConnection = _
                factory.CreateConnection()
            connection.ConnectionString = connectionString

            Using connection
                ' Define the query.
                Dim queryString As String = _
                  "SELECT CustomerID, CompanyName FROM Customers"

                'Create the select command.
                Dim command As DbCommand = _
                    factory.CreateCommand()
                command.CommandText = queryString
                command.Connection = connection

                ' Create the DbDataAdapter.
                Dim adapter As DbDataAdapter = _
                    factory.CreateDataAdapter()
                adapter.SelectCommand = command

                ' Create the DbCommandBuilder.
                Dim builder As DbCommandBuilder = _
                  factory.CreateCommandBuilder()
                builder.DataAdapter = adapter

                ' Get the insert, update and delete commands.
                adapter.InsertCommand = builder.GetInsertCommand()
                adapter.UpdateCommand = builder.GetUpdateCommand()
                adapter.DeleteCommand = builder.GetDeleteCommand()

                ' Display the CommandText for each command.
                Console.WriteLine("InsertCommand: {0}", _
                  adapter.InsertCommand.CommandText)
                Console.WriteLine("UpdateCommand: {0}", _
                  adapter.UpdateCommand.CommandText)
                Console.WriteLine("DeleteCommand: {0}", _
                  adapter.DeleteCommand.CommandText)

                ' Fill the DataTable
                Dim table As New DataTable
                adapter.Fill(table)

                ' Insert a new row.
                Dim newRow As DataRow = table.NewRow
                newRow("CustomerID") = "XYZZZ"
                newRow("CompanyName") = "XYZ Company"
                table.Rows.Add(newRow)

                adapter.Update(table)

                ' Display rows after insert.
                Console.WriteLine()
                Console.WriteLine("----List All Rows-----")
                Dim row As DataRow
                For Each row In table.Rows
                    Console.WriteLine("{0} {1}", row(0), row(1))
                Next
                Console.WriteLine("----After Insert-----")

                ' Edit an existing row.
                Dim editRow() As DataRow = _
                  table.Select("CustomerID = 'XYZZZ'")
                editRow(0)("CompanyName") = "XYZ Corporation"

                adapter.Update(table)

                ' Display rows after update.
                Console.WriteLine()
                For Each row In table.Rows
                    Console.WriteLine("{0} {1}", row(0), row(1))
                Next
                Console.WriteLine("----After Update-----")

                ' Delete a row.
                Dim deleteRow() As DataRow = _
                  table.Select("CustomerID = 'XYZZZ'")
                For Each row In deleteRow
                    row.Delete()
                Next

                adapter.Update(table)
                table.AcceptChanges()

                ' Display each row and column value after delete.
                Console.WriteLine()
                For Each row In table.Rows
                    Console.WriteLine("{0} {1}", row(0), row(1))
                Next
                Console.WriteLine("----After Delete-----")
                Console.WriteLine("Customer XYZZZ was deleted.")
            End Using

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

Gestion des paramètres

Les fournisseurs de données .NET Framework gèrent le nommage et la spécification des paramètres et des espaces réservés de paramètres différemment. Cette syntaxe est adaptée à une source de données spécifique, comme décrit dans le tableau suivant.

Fournisseur de données Syntaxe de nommage des paramètres
SqlClient Utilise des paramètres nommés dans le format @nom de paramètre.
OracleClient Utilise des paramètres nommés au format :parmname (ou parmname).
OleDb Utilise des marqueurs de paramètre positionnels indiqués par un point d’interrogation (?).
Odbc Utilise des marqueurs de paramètre positionnels indiqués par un point d’interrogation (?).

Le modèle de fabrique n’est pas utile pour créer des objets DbCommand et DbDataAdapter paramétrés. Vous devez créer une branche dans votre code pour créer des paramètres adaptés à votre fournisseur de données.

Importante

Il n'est pas recommandé, pour des raisons de sécurité, d'éviter complètement les paramètres spécifiques au fournisseur en utilisant la concaténation de chaînes pour construire des instructions SQL directes. L’utilisation de la concaténation de chaînes au lieu de paramètres laisse votre application vulnérable aux attaques par injection SQL.

Voir aussi