本文章以一個表為例,要轉多個表則可將DataSet關聯多個表,下面給出完整代碼,包括引用以及main函數與復制函數。
要說明的是,必須先用Sql語句復制表結構,才能順利的使用以下代碼復制數據。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; namespace CopyData { class Program { static void Main( string [] args) { //要復制的表名 string table = "V_Position" ; //構造連接字符串 SqlConnectionStringBuilder builder1 = new SqlConnectionStringBuilder(); builder1.DataSource = ".\\CANFLY" ; //實例名稱為CANFLY builder1.InitialCatalog = "desdata" ; //目標數據庫 builder1.IntegratedSecurity = true ; //使用Windows身份驗證 SqlConnectionStringBuilder builder2 = new SqlConnectionStringBuilder(); builder2.DataSource = ".\\CANFLY" ; builder2.InitialCatalog = "bddata" ; //源數據庫 builder2.IntegratedSecurity = true ; //調用復制數據庫函數 InsertTable(builder1.ConnectionString, builder2.ConnectionString, table); } //參數為兩個數據庫的連接字符串 private static void InsertTable( string conString1, string conString2, string tabStr) { //連接數據庫 SqlConnection conn1 = new SqlConnection(); conn1.ConnectionString = conString1; conn1.Open(); SqlConnection conn2 = new SqlConnection(); conn2.ConnectionString = conString2; conn2.Open(); //填充DataSet1 SqlDataAdapter adapter1 = new SqlDataAdapter( "select * from " + tabStr, conn1); DataSet dataSet1 = new DataSet(); if (dataSet1 != null ) { adapter1.Fill(dataSet1, tabStr); } SqlDataAdapter adapter2 = new SqlDataAdapter( "select * from " + tabStr, conn2); DataSet dataSet2 = new DataSet(); SqlCommand cmd2 = new SqlCommand( "select count(*) from " + tabStr, conn2); Object res2 = cmd2.ExecuteScalar(); if (res2 != null ) { int nCount = Convert.ToInt32(res2.ToString()); if (nCount == 0) { conn1.Close(); conn2.Close(); return ; } } //填充DataSet2 if (dataSet2 != null ) { adapter2.Fill(dataSet2, tabStr); } //復制數據 for ( int j = 0; j < dataSet2.Tables[0].Rows.Count; j++) { dataSet1.Tables[0].LoadDataRow(dataSet2.Tables[0].Rows[j].ItemArray, false ); } //將DataSet變換顯示在與其關聯的目標數據庫 SqlCommandBuilder cb = new SqlCommandBuilder(adapter1); adapter1.Update(dataSet1, tabStr); cb.RefreshSchema(); Console.WriteLine( "表" + tabStr + "復制成功!" ); conn1.Close(); conn2.Close(); } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/u011421608/article/details/39957873