SoFunction
Updated on 2025-03-06

C# Use SQL DataAdapter data to adapt code instances

Data adaptation

The DataAdapter object is a bridge between the DataSet and the data source. It can establish and initialize data tables (i.e. DataTables) and execute SQL instructions on the data source. Combined with DataSet objects, it provides DataSet object access data source to execute SQL instructions, and combines with Dataset objects to provide Dataset object access data, which can be regarded as the core of Data object operation.

When using DataAdapter object, you only need to set two parameters of SQL command and database connection, and you can place the query result in a DataSet object;

Example:

Populate DataSet dataset: Implemented by DataAdapter's Fill method Prerequisite: There is a database MySql, which has a data table mytable01, and there is data in the table

using System;
using ;  //Reference namespaceusing ;
namespace DataAdapter
{
  class Program
  {
    static void Main(string[] args)
    {
      //Connect the database      string constr = "Server=. ;user=sa;pwd=sa;database=MySql";
      SqlConnection mycon = new SqlConnection(constr);
      try
      {
        ();
        string sql = "selecr * from mytable01";
        SqlDataAdapter myda = new SqlDataAdapter(sql, mycon);
        DataSet myds = new DataSet();
        (myds,"mytable01");
        ("Fill successfully");
        OutValues(myds);
        ();
      }
      catch(Exception ex)
      {
        (());
      }
      finally
      {
        ();
      }
     } 
    public static void OutValues(DataSet ds)
    {
      foreach (DataTable dt in )
      {
        ("Table Name"+);
        foreach (DataRow row in )
        {
          foreach (DataColumn col in )
          {
            (row[col] + "\t");
          }
          ();
        }
      }
    }    
  }
}

The DataAdapter object can be used to execute command operations in a database, and contains four different execution commands, as follows:

  • SelectCommand: Used to select records in the data source
  • InsertCommand: Used to insert a new record into the data source
  • UpdateCommand: Used to update the data source
  • DeleteCommand: Used to delete records in the data source

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links