C#同步SQL Server資料庫中的資料--資料庫同步工具[同步新資料],

來源:互聯網
上載者:User

C#同步SQL Server資料庫中的資料--資料庫同步工具[同步新資料],
C#同步SQL Server資料庫中的資料1. 先寫個sql處理類:

using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;using System.Text;namespace PinkDatabaseSync{    class DBUtility : IDisposable    {        private string Server;        private string Database;        private string Uid;        private string Password;        private string connectionStr;        private SqlConnection mySqlConn;        public void EnsureConnectionIsOpen()        {            if (mySqlConn == null)            {                mySqlConn = new SqlConnection(this.connectionStr);                mySqlConn.Open();            }            else if (mySqlConn.State == ConnectionState.Closed)            {                mySqlConn.Open();            }        }        public DBUtility(string server, string database, string uid, string password)        {            this.Server = server;            this.Database = database;            this.Uid = uid;            this.Password = password;            this.connectionStr = "Server=" + this.Server + ";Database=" + this.Database + ";User Id=" + this.Uid + ";Password=" + this.Password;        }        public int ExecuteNonQueryForMultipleScripts(string sqlStr)        {            this.EnsureConnectionIsOpen();            SqlCommand cmd = mySqlConn.CreateCommand();            cmd.CommandType = CommandType.Text;            cmd.CommandText = sqlStr;            return cmd.ExecuteNonQuery();        }        public int ExecuteNonQuery(string sqlStr)        {            this.EnsureConnectionIsOpen();            SqlCommand cmd = new SqlCommand(sqlStr, mySqlConn);            cmd.CommandType = CommandType.Text;            return cmd.ExecuteNonQuery();        }        public object ExecuteScalar(string sqlStr)        {            this.EnsureConnectionIsOpen();            SqlCommand cmd = new SqlCommand(sqlStr, mySqlConn);            cmd.CommandType = CommandType.Text;            return cmd.ExecuteScalar();        }        public DataSet ExecuteDS(string sqlStr)        {            DataSet ds = new DataSet();            this.EnsureConnectionIsOpen();            SqlDataAdapter sda= new SqlDataAdapter(sqlStr,mySqlConn);            sda.Fill(ds);            return ds;        }        public void BulkCopyTo(string server, string database, string uid, string password, string tableName, string primaryKeyName)        {            string connectionString = "Server=" + server + ";Database=" + database + ";User Id=" + uid + ";Password=" + password;            // Create destination connection            SqlConnection destinationConnector = new SqlConnection(connectionString);            SqlCommand cmd = new SqlCommand("SELECT * FROM " + tableName, destinationConnector);            // Open source and destination connections.            this.EnsureConnectionIsOpen();            destinationConnector.Open();            SqlDataReader readerSource = cmd.ExecuteReader();            bool isSourceContainsData = false;            string whereClause = " where ";            while (readerSource.Read())            {                isSourceContainsData = true;                whereClause += " " + primaryKeyName + "!=" + readerSource[primaryKeyName].ToString() + " and ";            }            whereClause = whereClause.Remove(whereClause.Length - " and ".Length, " and ".Length);            readerSource.Close();            whereClause = isSourceContainsData ? whereClause : string.Empty;            // Select data from Products table            cmd = new SqlCommand("SELECT * FROM " + tableName + whereClause, mySqlConn);            // Execute reader            SqlDataReader reader = cmd.ExecuteReader();            // Create SqlBulkCopy            SqlBulkCopy bulkData = new SqlBulkCopy(destinationConnector);            // Set destination table name            bulkData.DestinationTableName = tableName;            // Write data            bulkData.WriteToServer(reader);            // Close objects            bulkData.Close();            destinationConnector.Close();            mySqlConn.Close();        }        public void Dispose()        {            if (mySqlConn != null)                mySqlConn.Close();        }    }}


2. 再寫個資料庫類型類:
using System;using System.Collections.Generic;using System.Text;namespace PinkDatabaseSync{    public class SQLDBSystemType    {        public static Dictionary<string, string> systemTypeDict        {            get{            var systemTypeDict = new Dictionary<string, string>();            systemTypeDict.Add("34", "image");            systemTypeDict.Add("35", "text");            systemTypeDict.Add("36", "uniqueidentifier");            systemTypeDict.Add("40", "date");            systemTypeDict.Add("41", "time");            systemTypeDict.Add("42", "datetime2");            systemTypeDict.Add("43", "datetimeoffset");            systemTypeDict.Add("48", "tinyint");            systemTypeDict.Add("52", "smallint");            systemTypeDict.Add("56", "int");            systemTypeDict.Add("58", "smalldatetime");            systemTypeDict.Add("59", "real");            systemTypeDict.Add("60", "money");            systemTypeDict.Add("61", "datetime");            systemTypeDict.Add("62", "float");            systemTypeDict.Add("98", "sql_variant");            systemTypeDict.Add("99", "ntext");            systemTypeDict.Add("104", "bit");            systemTypeDict.Add("106", "decimal");            systemTypeDict.Add("108", "numeric");            systemTypeDict.Add("122", "smallmoney");            systemTypeDict.Add("127", "bigint");            systemTypeDict.Add("240-128", "hierarchyid");            systemTypeDict.Add("240-129", "geometry");            systemTypeDict.Add("240-130", "geography");            systemTypeDict.Add("165", "varbinary");            systemTypeDict.Add("167", "varchar");            systemTypeDict.Add("173", "binary");            systemTypeDict.Add("175", "char");            systemTypeDict.Add("189", "timestamp");            systemTypeDict.Add("231", "nvarchar");            systemTypeDict.Add("239", "nchar");            systemTypeDict.Add("241", "xml");            systemTypeDict.Add("231-256", "sysname");            return systemTypeDict;            }        }    }}


3. 寫個同步資料庫中的資料:
public void BulkCopyTo(string server, string database, string uid, string password, string tableName, string primaryKeyName)        {            string connectionString = "Server=" + server + ";Database=" + database + ";User Id=" + uid + ";Password=" + password;            // Create destination connection            SqlConnection destinationConnector = new SqlConnection(connectionString);            SqlCommand cmd = new SqlCommand("SELECT * FROM " + tableName, destinationConnector);            // Open source and destination connections.            this.EnsureConnectionIsOpen();            destinationConnector.Open();            SqlDataReader readerSource = cmd.ExecuteReader();            bool isSourceContainsData = false;            string whereClause = " where ";            while (readerSource.Read())            {                isSourceContainsData = true;                whereClause += " " + primaryKeyName + "!=" + readerSource[primaryKeyName].ToString() + " and ";            }            whereClause = whereClause.Remove(whereClause.Length - " and ".Length, " and ".Length);            readerSource.Close();            whereClause = isSourceContainsData ? whereClause : string.Empty;            // Select data from Products table            cmd = new SqlCommand("SELECT * FROM " + tableName + whereClause, mySqlConn);            // Execute reader            SqlDataReader reader = cmd.ExecuteReader();            // Create SqlBulkCopy            SqlBulkCopy bulkData = new SqlBulkCopy(destinationConnector);            // Set destination table name            bulkData.DestinationTableName = tableName;            // Write data            bulkData.WriteToServer(reader);            // Close objects            bulkData.Close();            destinationConnector.Close();            mySqlConn.Close();        }


 

4. 最後執行同步函數:
private void SyncDB_Click(object sender, EventArgs e)        {            string server = "localhost";            string dbname = "pinkCRM";            string uid = "sa";            string password = "password";            string server2 = "server2";            string dbname2 = "pinkCRM2";            string uid2 = "sa";            string password2 = "password2";            try            {                LogView.Text = "DB data is syncing!";                DBUtility db = new DBUtility(server, dbname, uid, password);                DataSet ds = db.ExecuteDS("SELECT sobjects.name FROM sysobjects sobjects WHERE sobjects.xtype = 'U'");                DataRowCollection drc = ds.Tables[0].Rows;                foreach (DataRow dr in drc)                {                    string tableName = dr[0].ToString();                    LogView.Text = LogView.Text + Environment.NewLine + " syncing table:" + tableName + Environment.NewLine;                    DataSet ds2 = db.ExecuteDS("SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo." + tableName + "')");                    DataRowCollection drc2 = ds2.Tables[0].Rows;                    string primaryKeyName = drc2[0]["name"].ToString();                    db.BulkCopyTo(server2, dbname2, uid2, password2, tableName, primaryKeyName);                                     LogView.Text = LogView.Text +"Done sync data for table:"+ tableName+ Environment.NewLine;                }                MessageBox.Show("Done sync db data successfully!");            }            catch (Exception exc)            {                MessageBox.Show(exc.ToString());            }        }

註: 這裡唯寫了對已有資料的不再插入資料,可以再提高為如果有資料更新,可以進行更新,那麼一個資料庫同步工具就可以完成了!


一個C語言冒泡排序法的簡單程式

main()
{
int i,j,temp;
int a[10];
for(i=0;i<10;i++)
scanf ("%d,",&a[i]);
for(j=0;j<=9;j++)
{ for (i=0;i<10-j;i++)
if (a[i]>a[i+1])
{ temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;}
}
for(i=1;i<11;i++)
printf("%5d,",a[i] );
printf("\n");
}

--------------
冒泡演算法
冒泡排序的演算法分析與改進
交換排序的基本思想是:兩兩比較待排序記錄的關鍵字,發現兩個記錄的次序相反時即進行交換,直到沒有反序的記錄為止。
應用交換排序基本思想的主要排序方法有:冒泡排序和快速排序。

冒泡排序

1、排序方法
將被排序的記錄數組R[1..n]垂直排列,每個記錄R看作是重量為R.key的氣泡。根據輕氣泡不能在重氣泡之下的原則,從下往上掃描數組R:凡掃描到違反本原則的輕氣泡,就使其向上"飄浮"。如此反覆進行,直到最後任何兩個氣泡都是輕者在上,重者在下為止。
(1)初始
R[1..n]為無序區。

(2)第一趟掃描
從無序區底部向上依次比較相鄰的兩個氣泡的重量,若發現輕者在下、重者在上,則交換二者的位置。即依次比較(R[n],R[n-1]),(R[n-1],R[n-2]),…,(R[2],R[1]);對於每對氣泡(R[j+1],R[j]),若R[j+1].key<R[j].key,則交換R[j+1]和R[j]的內容。
第一趟掃描完畢時,"最輕"的氣泡就飄浮到該區間的頂部,即關鍵字最小的記錄被放在最高位置R[1]上。

(3)第二趟掃描
掃描R[2..n]。掃描完畢時,"次輕"的氣泡飄浮到R[2]的位置上……
最後,經過n-1 趟掃描可得到有序區R[1..n]
注意:
第i趟掃描時,R[1..i-1]和R[i..n]分別為當前的有序區和無序區。掃描仍是從無序區底部向上直至該區頂部。掃描完畢時,該區中最輕氣泡飄浮到頂部位置R上,結果是R[1..i]變為新的有序區。

2、冒泡排序過程樣本
對關鍵字序列為49 38 65 97 76 13 27 49的檔案進行冒泡排序的過程

3、排序演算法
(1)分析
因為每一趟排序都使有序區增加了一個氣泡,在經過n-1趟排序之後,有序區中就有n-1個氣泡,而無序區中氣泡的重量總是大於等於有序區中氣泡的重量,所以整個冒泡排序過程至多需要進行n-1趟排序。
若在某一趟排序中未發現氣泡位置的交換,則說明待排序的無序區中所有氣泡均滿足輕者在上,重者在下的原則,因此,冒泡排序過程可在此趟排序後終止。為此,在下面給出的演算法中,引入一個布爾量exchange,在每趟排序開始前,先將其置為FALSE。若排序過程中發生了交換,則將其置為TRUE。各趟排序結束時檢查exchange,若未曾發生過交換則終止演算法,不再進行下一趟排序。

(2)具體演算法
void BubbleSort(SeqList R)
{ //R(l..n)是待排序的檔案,採用自下向上掃描,對R做冒泡排序
int i,j;
Boolean exchange; //交換標誌
for(i=1;i&......餘下全文>>
 
一個C語言冒泡排序法的簡單程式

main()
{
int i,j,temp;
int a[10];
for(i=0;i<10;i++)
scanf ("%d,",&a[i]);
for(j=0;j<=9;j++)
{ for (i=0;i<10-j;i++)
if (a[i]>a[i+1])
{ temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;}
}
for(i=1;i<11;i++)
printf("%5d,",a[i] );
printf("\n");
}

--------------
冒泡演算法
冒泡排序的演算法分析與改進
交換排序的基本思想是:兩兩比較待排序記錄的關鍵字,發現兩個記錄的次序相反時即進行交換,直到沒有反序的記錄為止。
應用交換排序基本思想的主要排序方法有:冒泡排序和快速排序。

冒泡排序

1、排序方法
將被排序的記錄數組R[1..n]垂直排列,每個記錄R看作是重量為R.key的氣泡。根據輕氣泡不能在重氣泡之下的原則,從下往上掃描數組R:凡掃描到違反本原則的輕氣泡,就使其向上"飄浮"。如此反覆進行,直到最後任何兩個氣泡都是輕者在上,重者在下為止。
(1)初始
R[1..n]為無序區。

(2)第一趟掃描
從無序區底部向上依次比較相鄰的兩個氣泡的重量,若發現輕者在下、重者在上,則交換二者的位置。即依次比較(R[n],R[n-1]),(R[n-1],R[n-2]),…,(R[2],R[1]);對於每對氣泡(R[j+1],R[j]),若R[j+1].key<R[j].key,則交換R[j+1]和R[j]的內容。
第一趟掃描完畢時,"最輕"的氣泡就飄浮到該區間的頂部,即關鍵字最小的記錄被放在最高位置R[1]上。

(3)第二趟掃描
掃描R[2..n]。掃描完畢時,"次輕"的氣泡飄浮到R[2]的位置上……
最後,經過n-1 趟掃描可得到有序區R[1..n]
注意:
第i趟掃描時,R[1..i-1]和R[i..n]分別為當前的有序區和無序區。掃描仍是從無序區底部向上直至該區頂部。掃描完畢時,該區中最輕氣泡飄浮到頂部位置R上,結果是R[1..i]變為新的有序區。

2、冒泡排序過程樣本
對關鍵字序列為49 38 65 97 76 13 27 49的檔案進行冒泡排序的過程

3、排序演算法
(1)分析
因為每一趟排序都使有序區增加了一個氣泡,在經過n-1趟排序之後,有序區中就有n-1個氣泡,而無序區中氣泡的重量總是大於等於有序區中氣泡的重量,所以整個冒泡排序過程至多需要進行n-1趟排序。
若在某一趟排序中未發現氣泡位置的交換,則說明待排序的無序區中所有氣泡均滿足輕者在上,重者在下的原則,因此,冒泡排序過程可在此趟排序後終止。為此,在下面給出的演算法中,引入一個布爾量exchange,在每趟排序開始前,先將其置為FALSE。若排序過程中發生了交換,則將其置為TRUE。各趟排序結束時檢查exchange,若未曾發生過交換則終止演算法,不再進行下一趟排序。

(2)具體演算法
void BubbleSort(SeqList R)
{ //R(l..n)是待排序的檔案,採用自下向上掃描,對R做冒泡排序
int i,j;
Boolean exchange; //交換標誌
for(i=1;i&......餘下全文>>
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.