Home > Database > Mysql Tutorial > How to Efficiently Retrieve a DataSet from a SQL Command Text in C#?

How to Efficiently Retrieve a DataSet from a SQL Command Text in C#?

Linda Hamilton
Release: 2024-12-20 20:56:10
Original
212 people have browsed it

How to Efficiently Retrieve a DataSet from a SQL Command Text in C#?

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;
            }
        }
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template