Generating a DataSet Directly from SQL Command Text
Accessing data from a database as a DataSet or DataTable is a fundamental task in programming applications. This question explores the most efficient approach for obtaining a DataSet directly from an SQL command text.
Using SqlDataAdapter
The key to this approach is utilizing SqlDataAdapter, a component that acts as a bridge between a database connection and a DataSet or DataTable. The code snippet provided demonstrates how to employ SqlDataAdapter:
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 code:
Conclusion
Using SqlDataAdapter is the most direct way to obtain a DataSet from SQL command text. It offers a simplified and efficient approach compared to manually converting a SqlDataReader to a DataSet.
The above is the detailed content of How Can I Efficiently Generate a DataSet Directly from an SQL Command String?. For more information, please follow other related articles on the PHP Chinese website!