Home >Database >Mysql Tutorial >How Can I Efficiently Retrieve a DataSet from a SQL Command Text?
When working with SQL commands, you often need to retrieve data into a DataSet or DataTable. While there are multiple approaches to accomplish this, there's an efficient and direct method that streamlines the process.
In the provided code example, a SqlConnection and SqlCommand are initialized, but the intention is to use a more direct route to get a DataSet or DataTable. To achieve this, the SqlDataAdapter class comes in handy. Here's the revised code:
public DataSet GetDataSet(string ConnectionString, string SQL) { using (SqlConnection conn = new SqlConnection(ConnectionString)) { using (SqlDataAdapter da = new SqlDataAdapter()) { using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = SQL; da.SelectCommand = cmd; DataSet ds = new DataSet(); da.Fill(ds); return ds; } } } }
In this revised code, we use using statements to ensure that the resources are disposed of properly. Here's a breakdown of the code:
Once this code is executed, a DataSet will be returned, containing the data from the SQL command you provided. Whether you prefer a DataSet or a DataTable, this direct approach provides a straightforward and efficient way to retrieve data from a SQL command.
The above is the detailed content of How Can I Efficiently Retrieve a DataSet from a SQL Command Text?. For more information, please follow other related articles on the PHP Chinese website!