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