SoFunction
Updated on 2025-03-06

C# implements the replication database C# transfers database A data to database B

This article takes one table as an example. To transfer multiple tables, you can associate DataSet with multiple tables. The complete code is given below, including references, main function and copy function.
It should be noted that you must first use the Sql statement to copy the table structure to successfully use the following code to copy the data.

using System; 
using ; 
using ; 
using ; 
using ; 
using ; 
using ; 
 
namespace CopyData 
{ 
 class Program 
 { 
  static void Main(string[] args) 
  { 
   //The table name to be copied   string table = "V_Position"; 
    
   //Construct the connection string   SqlConnectionStringBuilder builder1 = new SqlConnectionStringBuilder(); 
    = ".\\CANFLY";  //The instance name is CANFLY    = "desdata"; //Target database    = true;  //Use Windows authentication 
   SqlConnectionStringBuilder builder2 = new SqlConnectionStringBuilder(); 
    = ".\\CANFLY"; 
    = "bddata";  // Source database    = true; 
 
   //Calling the copy database function   InsertTable(, , table); 
  } 
   
  //The parameter is the connection string of two databases  private static void InsertTable(string conString1, string conString2, string tabStr) 
  { 
   //Connect the database   SqlConnection conn1 = new SqlConnection(); 
    = conString1; 
   (); 
 
   SqlConnection conn2 = new SqlConnection(); 
    = conString2; 
   (); 
 
   //Fill DataSet1   SqlDataAdapter adapter1 = new SqlDataAdapter("select * from " + tabStr, conn1); 
   DataSet dataSet1 = new DataSet(); 
 
   if (dataSet1 != null) 
   { 
    (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 = (); 
 
   if (res2 != null) 
   { 
    int nCount = Convert.ToInt32(()); 
    if (nCount == 0) 
    { 
     (); 
     (); 
     return; 
    } 
   } 
 
   //Fill DataSet2   if (dataSet2 != null) 
   { 
    (dataSet2, tabStr); 
   } 
 
   //Copy the data   for (int j = 0; j < [0].; j++) 
   { 
    [0].LoadDataRow([0].Rows[j].ItemArray, false); 
   } 
 
   // Display DataSet transformation in the target database associated with it   SqlCommandBuilder cb = new SqlCommandBuilder(adapter1); 
   (dataSet1, tabStr); 
   (); 
 
   ("surface" + tabStr + "Copy successfully!"); 
 
   (); 
   (); 
 
  } 
 } 
} 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.