Skip to content
Advertisement

Direct method from SQL command text to DataSet

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.

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement