Direct method from SQL command text to DataSet

C#SqlDataset

C# Problem Overview


What is the most direct route to get a DataSet if I have a sql command?

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet = GetDataSet(sqlCommand,connectionString);

GetDataSet()
{
   //...?
}

I started with SqlConnection and SqlCommand, but the closest thing I see in the API is SqlCommand.ExecuteReader(). With this method, I'll need to get a SqlDataReader and then convert this to a DataSet manually. I figure there is a more direct route to accomplish the task.

If easier, a DataTable will also fit my goal.

C# Solutions


Solution 1 - C#

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

Solution 2 - C#

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);

DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

Solution 3 - C#

public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";

public static DataSet LoaderDataSet(string StrSql)      
{
    SqlConnection cnn;            
    SqlDataAdapter dad;
    DataSet dts = new DataSet();
    cnn = new SqlConnection(textDataSource);
    dad = new SqlDataAdapter(StrSql, cnn);
    try
    {
        cnn.Open();
        dad.Fill(dts);
        cnn.Close();
        
        return dts;
    }
    catch (Exception)
    {

        return dts;
    }
    finally
    {
        dad.Dispose();
        dts = null;
        cnn = null;
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionP.Brian.MackeyView Question on Stackoverflow
Solution 1 - C#Adriano CarneiroView Answer on Stackoverflow
Solution 2 - C#jp2codeView Answer on Stackoverflow
Solution 3 - C#Snookger IsolationView Answer on Stackoverflow