Directly Retrieving a DataSet from SQL Command Text
To retrieve a DataSet directly from a SQL command text, the most efficient approach is to utilize the SqlDataAdapter class. This class acts as a bridge between a data source and a dataset, allowing data manipulation and retrieval.
To begin, create a SqlConnection object with the appropriate connection string. Next, instantiate an instance of SqlCommand within this connection to specify the SQL command text to execute. Associate the SqlCommand with the SqlDataAdapter as its SelectCommand.
Finally, create a DataSet to store the retrieved data. Use the SqlDataAdapter's Fill() method to populate the DataSet with data from the command execution.
Sample Code:
public DataSet GetDataSet(string ConnectionString, string SQL) { using (SqlConnection conn = new SqlConnection(ConnectionString)) { using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = SQL; using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); da.Fill(ds); return ds; } } } }
Calling the GetDataSet() method with the appropriate parameters will return a DataSet populated with data from the SQL command text. It's important to note that in a real-world application, it's generally recommended to use a "using" statement to ensure proper resource disposal.
The above is the detailed content of How to Efficiently Retrieve a DataSet from a SQL Command Text in C#?. For more information, please follow other related articles on the PHP Chinese website!