Home > Database > Mysql Tutorial > How to Directly Populate a DataSet or DataTable from SQL Using a Command?

How to Directly Populate a DataSet or DataTable from SQL Using a Command?

Patricia Arquette
Release: 2024-12-31 01:55:07
Original
889 people have browsed it

How to Directly Populate a DataSet or DataTable from SQL Using a Command?

Filling a DataSet or DataTable Directly from SQL Using a Command

To retrieve data from a SQL database and populate a DataSet or DataTable, you can use the following technique directly from a SQL command:

private DataSet GetDataSet(string sqlCommand, string connectionString)
{
    // Create a connection to the database
    using (var conn = new SqlConnection(connectionString))
    {
        // Create a new data adapter
        var da = new SqlDataAdapter(sqlCommand, conn);

        // Fill a new dataset with the results of the command
        var ds = new DataSet();
        da.Fill(ds);

        // Return the dataset
        return ds;
    }
}
Copy after login

This method takes a SQL command and a connection string as parameters and creates a SqlConnection object. It then creates a SqlDataAdapter using the specified command and connection. Finally, it fills a new DataSet with the results of the command and returns the dataset.

You can also use this method to fill a DataTable instead of a DataSet. To do this, simply pass the name of the table you want to fill as the second parameter to the Fill method:

private DataTable GetDataTable(string sqlCommand, string connectionString)
{
    // Create a connection to the database
    using (var conn = new SqlConnection(connectionString))
    {
        // Create a new data adapter
        var da = new SqlDataAdapter(sqlCommand, conn);

        // Fill a new datatable with the results of the command
        var dt = new DataTable();
        da.Fill(dt);

        // Return the datatable
        return dt;
    }
}
Copy after login

The above is the detailed content of How to Directly Populate a DataSet or DataTable from SQL Using a Command?. 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