如何从DATABASE C中填充表中的DATASET

时间:2019-02-12 11:05:57

标签: c# sql

我有一个包含三个表的数据库,我想将它们复制到一个数据集中,该怎么做?

public DataSet SelectDset()
        {
            try
            {
                string str = "SELECT * FROM Information_Schema.Tables";
                ds = new DataSet();
                Open();
                cmd = new SqlCommand(str, con);
                da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                da.Dispose();
                cmd.Dispose();
                Close();
                return ds;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                Close();
            }
        }

1 个答案:

答案 0 :(得分:0)

首先,此查询 “ SELECT * FROM Information_Schema.Tables” 将仅检索数据库中表和视图的列表,而不检索表中的记录。要将其限制为仅检索基表类型,您将必须包括一个WHERE子句,如下所示。

第二,要检索表中的所有记录,您将不得不遍历表列表并构建查询以检索记录(行)

您可以尝试

    public DataSet SelectDset()
    {
        DataTable dtTablesNames=new DataTable();      
        try
        {
            Open();
            //get the list of tables in the database into a DataTable
            sTablesNamesQuery="SELECT TABLE_NAME FROM INFORMATION_SCHEMA.Tables WHERE TABLE_TYPE = 'BASE TABLE' Order by TABLE_NAME";
            SqlDataAdapter sda1 = new SqlDataAdapter(sTablesNamesQuery, con);
            sda1.Fill(dtTablesNames);
            //               
            DataSet dsAllTables = new DataSet();
            StringBuilder sbQuery = "";
            //build the queries that will be used to retrieve the tables rows
            foreach (DataRow dr in dtTablesNames.Rows)
            {
                sbQuery.Append("SELECT * FROM " + dr["TABLE_NAME"].ToString()+";");                    
            }
            //
            SqlDataAdapter sda2 = new SqlDataAdapter(sbQuery, con);
            sda2.Fill(dsAllTables);
            sda1.Dispose();
            sda2.Dispose();
            Close();
            return dsAllTables;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
   }
相关问题