Unlike the common scenario of inserting C# DataTable data into a SQL table, this article explores the technique of extracting data from a SQL table into a C# DataTable.
To accomplish this data transfer, you can utilize the following C# code as a starting point:
using System; using System.Data; using System.Data.SqlClient; namespace DataTableFromSQL { class Program { static void Main(string[] args) { // Connection string to your database string connectionString = "your connection string here"; // SQL query to retrieve data string query = "select * from table"; // Create new SQL connection using (SqlConnection connection = new SqlConnection(connectionString)) { // Create command using query and connection using (SqlCommand command = new SqlCommand(query, connection)) { // Open the connection connection.Open(); // Create data adapter using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { // Create new DataTable DataTable dataTable = new DataTable(); // Fill DataTable with data from SQL table adapter.Fill(dataTable); // Iterate through rows and print column values foreach (DataRow row in dataTable.Rows) { foreach (DataColumn column in dataTable.Columns) { Console.WriteLine($"{column.ColumnName}: {row[column]}"); } } } } } } } }
In this code:
The above is the detailed content of How to Populate a C# DataTable from a SQL Server Table?. For more information, please follow other related articles on the PHP Chinese website!