Question

J'ai besoin d'apprendre ADO.NET pour créer des applications basées sur MS Office.J'ai beaucoup lu sur ADO.NET dans la bibliothèque MSDN, mais tout me semble plutôt compliqué.

Quelles sont les bases qu’il faut comprendre lors de l’utilisation d’ADO.NET ?Je pense que quelques mots clés suffiront pour me permettre d'organiser mon apprentissage.

Était-ce utile?

La solution

Il y a trois composants clés (en supposant que vous utilisiez SQL Server) :

  • SQLConnection
  • SqlCommand
  • SqlDataReader

(si vous utilisez autre chose, remplacez Sql avec "Quelque chose", comme MySqlConnection, OracleCommand)

Tout le reste est construit là-dessus.

Exemple 1:

using (SqlConnection connection = new SqlConnection("CONNECTION STRING"))
using (SqlCommand command = new SqlCommand())
{
  command.commandText = "SELECT Name FROM Users WHERE Status = @OnlineStatus";
  command.Connection = connection;
  command.Parameters.Add("@OnlineStatus", SqlDbType.Int).Value = 1; //replace with enum
  connection.Open();

  using (SqlDataReader dr = command.ExecuteReader))
  {
      List<string> onlineUsers = new List<string>();

      while (dr.Read())
      {
         onlineUsers.Add(dr.GetString(0));
      }
  }
}

Exemple 2 :

using (SqlConnection connection = new SqlConnection("CONNECTION STRING"))
using (SqlCommand command = new SqlCommand())
{
  command.commandText = "DELETE FROM Users where Email = @Email";
  command.Connection = connection;
  command.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = "user@host.com";
  connection.Open();
  command.ExecuteNonQuery();
}

Autres conseils

Une autre façon d'obtenir un objet de commande est d'appeler connection.CreateCommand().

De cette façon, vous ne devriez pas avoir à définir le Connection propriété sur l’objet de commande.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top