Thursday, July 21, 2022

Bulk insert in a table From Different Server C# code

 C# Code for data collection from different servers.

it will get a list of server credentials from a table. This table contains the source server login credentials.




in c# asp.net there will be a foreach loop and it will execute the operations.


 foreach (var v in List_Members)

                {

                     

                    string connectionString = @"Data Source=" + v.ServerIP + ";Initial Catalog=" + v.DatabaseName + ";User ID=" + v.User + ";Password=" + v.Password  ;

 

                    var ServerIP = @"192.192.192.188\MSSQLSERVER2016";

                    var DatabaseName = "gBankerSMSDb";

                    var User = "gBanker6";

                    var Password = "gBanker6";


                    string csDest = @"Data Source=" + ServerIP + ";Initial Catalog=" + DatabaseName + ";User ID=" + User + ";Password=" + Password;



                    // Create source connection

                    SqlConnection source = new SqlConnection(connectionString);

                    // Create destination connection

                    SqlConnection destination = new SqlConnection(csDest);


                    // Clean up destination table. Your destination database must have the

                    // table with schema which you are copying data to.

                    // Before executing this code, you must create a table BulkDataTable

                    // in your database where you are trying to copy data to.


                    //SqlCommand cmd = new SqlCommand("DELETE FROM MemberPortal_Bulk", destination);

                    SqlCommand cmd = new SqlCommand("SELECT 1 ", destination);

                    // Open source and destination connections.

                    source.Open();

                    destination.Open();

                    cmd.ExecuteNonQuery();

                    // Select data from Products table

                    cmd = new SqlCommand(@"SELECT TOP 5000 * FROM MemberPortal", source);

                    // Execute reader

                    SqlDataReader reader = cmd.ExecuteReader();

                    // Create SqlBulkCopy

                    SqlBulkCopy bulkData = new SqlBulkCopy(destination);

                    // Set destination table name

                    bulkData.DestinationTableName = "MemberPortal_Bulk";

                    // Write data

                    bulkData.WriteToServer(reader);

                    // Close objects

                    bulkData.Close();

                    destination.Close();

                    source.Close();

                }


This code will keep adding data in 192.192.192.188\MSSQLSERVER2016 server. Keep adding data in MemberPortal_Bulk Table database gBankerSMSDb

No comments:

Post a Comment

Screen Record

 Windows Screen Record WindowsKey+ Alt + R Recording Starts.