Home >Database >Mysql Tutorial >How Can I Directly Populate a DataSet from a SQL Command?
Question:
How can I efficiently obtain a DataSet by directly executing a SQL command?
Introduction:
Working with relational data often involves retrieving data from a database using SQL queries. To efficiently populate a DataSet with the results of a SQL command, there are various approaches available.
Direct Method Using SqlDataAdapter:
The most direct method to get a DataSet from a SQL command is to use a SqlDataAdapter. The code snippet below provides a direct implementation:
public DataSet GetDataSet(string ConnectionString, string SQL) { // Create a SQL connection SqlConnection conn = new SqlConnection(ConnectionString); // Create a data adapter to bridge SQL command to DataSet SqlDataAdapter da = new SqlDataAdapter(); // Create a SQL command to execute SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = SQL; da.SelectCommand = cmd; // Create a DataSet to hold the data DataSet ds = new DataSet(); // Fill the DataSet with data da.Fill(ds); // Return the DataSet return ds; }
Explanation:
The above is the detailed content of How Can I Directly Populate a DataSet from a SQL Command?. For more information, please follow other related articles on the PHP Chinese website!