To retrieve data from a SQL database and populate a DataSet or DataTable, you can use the following technique directly from a SQL command:
private DataSet GetDataSet(string sqlCommand, string connectionString) { // Create a connection to the database using (var conn = new SqlConnection(connectionString)) { // Create a new data adapter var da = new SqlDataAdapter(sqlCommand, conn); // Fill a new dataset with the results of the command var ds = new DataSet(); da.Fill(ds); // Return the dataset return ds; } }
This method takes a SQL command and a connection string as parameters and creates a SqlConnection object. It then creates a SqlDataAdapter using the specified command and connection. Finally, it fills a new DataSet with the results of the command and returns the dataset.
You can also use this method to fill a DataTable instead of a DataSet. To do this, simply pass the name of the table you want to fill as the second parameter to the Fill method:
private DataTable GetDataTable(string sqlCommand, string connectionString) { // Create a connection to the database using (var conn = new SqlConnection(connectionString)) { // Create a new data adapter var da = new SqlDataAdapter(sqlCommand, conn); // Fill a new datatable with the results of the command var dt = new DataTable(); da.Fill(dt); // Return the datatable return dt; } }
The above is the detailed content of How to Directly Populate a DataSet or DataTable from SQL Using a Command?. For more information, please follow other related articles on the PHP Chinese website!