Home >Backend Development >C++ >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:
Create a DataTable object:
DataTable dataTable = new DataTable();
Establish a connection to the SQL database:
string connString = @"your connection string here"; SqlConnection conn = new SqlConnection(connString);
Define an SQL query to retrieve the data:
string query = "select * from table";
Create a SqlCommand object to execute the query:
SqlCommand cmd = new SqlCommand(query, conn);
Open the database connection:
conn.Open();
Create a SqlDataAdapter object to bridge the connection and the DataTable:
SqlDataAdapter da = new SqlDataAdapter(cmd);
Use the Fill() method to populate the DataTable:
da.Fill(dataTable);
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!