DataTable.Clone 方法:克隆 DataTable 的结构,包括所有 DataTable 架构和约束。

DataTable.Copy 方法:复制该 DataTable 的结构和数据。

我们可以编写如下的程序,进行验证:
复制代码 代码如下:
        static string connStr = "Server=.\\sqlexpress;Initial Catalog=hr;Integrated Security=True";

        static void Clone()
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "select * from emp";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DataTable dtClone = dt.Clone();
                Print(dtClone);
            }
        }

        private static void Print(DataTable dtClone)
        {
            foreach (DataColumn col in dtClone.Columns)
            {
                Console.Write(col.DataType+"\t");
            }
            Console.WriteLine();
            foreach (DataRow row in dtClone.Rows)
            {
                Console.Write(row[0] + "\t" + row[1] + "\t" + row[2] + "\n");
            }
            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            Clone();//仅仅复制表结构
            Copy();//复制表结构及数据
            Console.ReadKey();
        }

        private static void Copy()
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "select * from emp";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DataTable dtCopy = dt.Copy();
                Print(dtCopy);
            }
        }
    }

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!