从SQL命令文本到D的直接方法

如果我有sql命令,最直接的获取数据集的途径是什么?

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

DataSet = GetDataSet(sqlCommand,connectionString);

GetDataSet()
{
   //...?
}

我从SqlConnectionDataTable开始,但是我在API中看到的最接近的东西是SqlCommand.ExecuteReader()。通过这种方法,我需要获取SqlDataReader,然后手动将其转换为DataSet。 我认为完成任务有更直接的途径。

如果更容易,则DataTable也将适合我的目标。

P.Brian.Mackey asked 2020-02-21T13:28:39Z
3个解决方案
86 votes
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;
}
Adrian Carneiro answered 2020-02-21T13:28:50Z
25 votes

刚完成。

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;
}
jp2code answered 2020-02-21T13:29:10Z
0 votes
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;
    }
}
Snookger Isolation answered 2020-02-21T13:29:26Z
translate from https://stackoverflow.com:/questions/6584817/direct-method-from-sql-command-text-to-dataset