繁体   English   中英

如何在 DATABASE C# 中的表中填充 DATASET

[英]How to fill DATASET in tables from DATABASE C #

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

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();
            }
        }

首先,这个查询“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);
        }
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM