Home >Backend Development >C++ >How to Populate a C# DataTable from an SQL Table?

How to Populate a C# DataTable from an SQL Table?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 13:36:21430browse

How to Populate a C# DataTable from an SQL Table?

Populating a C# DataTable from an SQL Table

Many discussions focus on transferring DataTable contents into SQL tables. However, the reverse process of reading data from an SQL table into a C# DataTable is equally important.

Solution:

To retrieve SQL table data into a DataTable using C#, follow these steps:

  1. Create a DataTable object:

    DataTable dataTable = new DataTable();
  2. Establish a connection to the SQL database:

    string connString = @"your connection string here";
    SqlConnection conn = new SqlConnection(connString);
  3. Define an SQL query to retrieve the data:

    string query = "select * from table";
  4. Create a SqlCommand object to execute the query:

    SqlCommand cmd = new SqlCommand(query, conn);
  5. Open the database connection:

    conn.Open();
  6. Create a SqlDataAdapter object to bridge the connection and the DataTable:

    SqlDataAdapter da = new SqlDataAdapter(cmd);
  7. Use the Fill() method to populate the DataTable:

    da.Fill(dataTable);
  8. Close the database connection and dispose the data adapter:

    conn.Close();
    da.Dispose();

The above is the detailed content of How to Populate a C# DataTable from an SQL Table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn