Direct method from SQL command text to DataSet

前端 未结 3 677
小蘑菇
小蘑菇 2020-11-30 06:08

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

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


        
相关标签:
3条回答
  • 2020-11-30 06:54
    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 06:59
    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;
    }
    
    0 讨论(0)
  • 2020-11-30 07:08

    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;
    }
    
    0 讨论(0)
提交回复
热议问题