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

How to Populate a C# DataTable with Data from a SQL Server Table?

Patricia Arquette
Release: 2024-12-31 02:20:10
Original
309 people have browsed it

How to Populate a C# DataTable with Data from a SQL Server Table?

Populating a C# DataTable with SQL Table Data

When working with relational databases, the need to retrieve data from SQL tables into a C# DataTable often arises. This article aims to provide a clear solution for accomplishing this task.

Solution

The process involves establishing a connection to the SQL database, executing a query, and populating the C# DataTable with the returned result set. Below is a simplified code snippet demonstrating the steps:

using System;
using System.Data;
using System.Data.SqlClient;

namespace DataTableFromSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            // Connection string to the SQL database
            string connectionString = @"Data Source=.;Initial Catalog=YourDatabase;Integrated Security=True;";

            // SQL query to retrieve data
            string query = "SELECT * FROM YourTable";

            // Create a DataTable to store the result
            DataTable dataTable = new DataTable();

            // Establish a connection to the database
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                // Create a command object
                SqlCommand cmd = new SqlCommand(query, conn);

                // Open the connection
                conn.Open();

                // Create a data adapter
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                // Fill the DataTable with the result set
                adapter.Fill(dataTable);

                // Close the connection
                conn.Close();
            }
        }
    }
}
Copy after login

Once the code is executed, the dataTable variable will contain the queried data from the SQL table. This DataTable can then be used for further processing or display within the C# application.

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

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template