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(); } } } }
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!