搜索
查看: 1437|回复: 0

【SQLServer】C#同步SQLServer数据库中的数据--数据库同步工具[同步新数据]

[复制链接]

183

主题

8

回帖

820

积分

高级会员

积分
820
发表于 2014-10-23 14:06:46 | 显示全部楼层 |阅读模式
本帖最后由 MEI 于 2014-10-23 14:08 编辑

C#同步SQL Server数据库中的数据

1. 先写个sql处理类:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Text;

  6. namespace PinkDatabaseSync
  7. {
  8.     class DBUtility : IDisposable
  9.     {
  10.         private string Server;
  11.         private string Database;
  12.         private string Uid;
  13.         private string Password;
  14.         private string connectionStr;
  15.         private SqlConnection mySqlConn;

  16.         public void EnsureConnectionIsOpen()
  17.         {
  18.             if (mySqlConn == null)
  19.             {
  20.                 mySqlConn = new SqlConnection(this.connectionStr);
  21.                 mySqlConn.Open();
  22.             }
  23.             else if (mySqlConn.State == ConnectionState.Closed)
  24.             {
  25.                 mySqlConn.Open();
  26.             }
  27.         }

  28.         public DBUtility(string server, string database, string uid, string password)
  29.         {
  30.             this.Server = server;
  31.             this.Database = database;
  32.             this.Uid = uid;
  33.             this.Password = password;
  34.             this.connectionStr = "Server=" + this.Server + ";Database=" + this.Database + ";User Id=" + this.Uid + ";Password=" + this.Password;
  35.         }

  36.         public int ExecuteNonQueryForMultipleScripts(string sqlStr)
  37.         {
  38.             this.EnsureConnectionIsOpen();
  39.             SqlCommand cmd = mySqlConn.CreateCommand();
  40.             cmd.CommandType = CommandType.Text;
  41.             cmd.CommandText = sqlStr;
  42.             return cmd.ExecuteNonQuery();
  43.         }
  44.         public int ExecuteNonQuery(string sqlStr)
  45.         {
  46.             this.EnsureConnectionIsOpen();
  47.             SqlCommand cmd = new SqlCommand(sqlStr, mySqlConn);
  48.             cmd.CommandType = CommandType.Text;
  49.             return cmd.ExecuteNonQuery();
  50.         }


  51.         public object ExecuteScalar(string sqlStr)
  52.         {
  53.             this.EnsureConnectionIsOpen();
  54.             SqlCommand cmd = new SqlCommand(sqlStr, mySqlConn);
  55.             cmd.CommandType = CommandType.Text;
  56.             return cmd.ExecuteScalar();
  57.         }

  58.         public DataSet ExecuteDS(string sqlStr)
  59.         {
  60.             DataSet ds = new DataSet();
  61.             this.EnsureConnectionIsOpen();
  62.             SqlDataAdapter sda= new SqlDataAdapter(sqlStr,mySqlConn);
  63.             sda.Fill(ds);
  64.             return ds;
  65.         }

  66.         public void BulkCopyTo(string server, string database, string uid, string password, string tableName, string primaryKeyName)
  67.         {
  68.             string connectionString = "Server=" + server + ";Database=" + database + ";User Id=" + uid + ";Password=" + password;
  69.             // Create destination connection
  70.             SqlConnection destinationConnector = new SqlConnection(connectionString);

  71.             SqlCommand cmd = new SqlCommand("SELECT * FROM " + tableName, destinationConnector);
  72.             // Open source and destination connections.
  73.             this.EnsureConnectionIsOpen();
  74.             destinationConnector.Open();

  75.             SqlDataReader readerSource = cmd.ExecuteReader();
  76.             bool isSourceContainsData = false;
  77.             string whereClause = " where ";
  78.             while (readerSource.Read())
  79.             {
  80.                 isSourceContainsData = true;
  81.                 whereClause += " " + primaryKeyName + "=" + readerSource[primaryKeyName].ToString() + " or ";
  82.             }
  83.             whereClause = whereClause.Remove(whereClause.Length - " or ".Length, " or ".Length);
  84.             readerSource.Close();

  85.             whereClause = isSourceContainsData ? whereClause : string.Empty;

  86.             // Select data from Products table
  87.             cmd = new SqlCommand("SELECT * FROM " + tableName + whereClause, mySqlConn);
  88.             // Execute reader
  89.             SqlDataReader reader = cmd.ExecuteReader();
  90.             // Create SqlBulkCopy
  91.             SqlBulkCopy bulkData = new SqlBulkCopy(destinationConnector);
  92.             // Set destination table name
  93.             bulkData.DestinationTableName = tableName;
  94.             // Write data
  95.             bulkData.WriteToServer(reader);
  96.             // Close objects
  97.             bulkData.Close();
  98.             destinationConnector.Close();
  99.             mySqlConn.Close();
  100.         }

  101.         public void Dispose()
  102.         {
  103.             if (mySqlConn != null)
  104.                 mySqlConn.Close();
  105.         }
  106.     }
  107. }
复制代码
2. 再写个数据库类型类:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;

  4. namespace PinkDatabaseSync
  5. {
  6.     public class SQLDBSystemType
  7.     {
  8.         public static Dictionary<string, string> systemTypeDict
  9.         {
  10.             get{
  11.             var systemTypeDict = new Dictionary<string, string>();
  12.             systemTypeDict.Add("34", "image");
  13.             systemTypeDict.Add("35", "text");
  14.             systemTypeDict.Add("36", "uniqueidentifier");
  15.             systemTypeDict.Add("40", "date");
  16.             systemTypeDict.Add("41", "time");
  17.             systemTypeDict.Add("42", "datetime2");
  18.             systemTypeDict.Add("43", "datetimeoffset");
  19.             systemTypeDict.Add("48", "tinyint");
  20.             systemTypeDict.Add("52", "smallint");
  21.             systemTypeDict.Add("56", "int");
  22.             systemTypeDict.Add("58", "smalldatetime");
  23.             systemTypeDict.Add("59", "real");
  24.             systemTypeDict.Add("60", "money");
  25.             systemTypeDict.Add("61", "datetime");
  26.             systemTypeDict.Add("62", "float");
  27.             systemTypeDict.Add("98", "sql_variant");
  28.             systemTypeDict.Add("99", "ntext");
  29.             systemTypeDict.Add("104", "bit");
  30.             systemTypeDict.Add("106", "decimal");
  31.             systemTypeDict.Add("108", "numeric");
  32.             systemTypeDict.Add("122", "smallmoney");
  33.             systemTypeDict.Add("127", "bigint");
  34.             systemTypeDict.Add("240-128", "hierarchyid");
  35.             systemTypeDict.Add("240-129", "geometry");
  36.             systemTypeDict.Add("240-130", "geography");
  37.             systemTypeDict.Add("165", "varbinary");
  38.             systemTypeDict.Add("167", "varchar");
  39.             systemTypeDict.Add("173", "binary");
  40.             systemTypeDict.Add("175", "char");
  41.             systemTypeDict.Add("189", "timestamp");
  42.             systemTypeDict.Add("231", "nvarchar");
  43.             systemTypeDict.Add("239", "nchar");
  44.             systemTypeDict.Add("241", "xml");
  45.             systemTypeDict.Add("231-256", "sysname");
  46.             return systemTypeDict;
  47.             }
  48.         }
  49.     }
  50. }
复制代码
3. 写个同步数据库中的数据:
  1. public void BulkCopyTo(string server, string database, string uid, string password, string tableName, string primaryKeyName)
  2.         {
  3.             string connectionString = "Server=" + server + ";Database=" + database + ";User Id=" + uid + ";Password=" + password;
  4.             // Create destination connection
  5.             SqlConnection destinationConnector = new SqlConnection(connectionString);

  6.             SqlCommand cmd = new SqlCommand("SELECT * FROM " + tableName, destinationConnector);
  7.             // Open source and destination connections.
  8.             this.EnsureConnectionIsOpen();
  9.             destinationConnector.Open();

  10.             SqlDataReader readerSource = cmd.ExecuteReader();
  11.             bool isSourceContainsData = false;
  12.             string whereClause = " where ";
  13.             while (readerSource.Read())
  14.             {
  15.                 isSourceContainsData = true;
  16.                 whereClause += " " + primaryKeyName + "=" + readerSource[primaryKeyName].ToString() + " or ";
  17.             }
  18.             whereClause = whereClause.Remove(whereClause.Length - " or ".Length, " or ".Length);
  19.             readerSource.Close();

  20.             whereClause = isSourceContainsData ? whereClause : string.Empty;

  21.             // Select data from Products table
  22.             cmd = new SqlCommand("SELECT * FROM " + tableName + whereClause, mySqlConn);
  23.             // Execute reader
  24.             SqlDataReader reader = cmd.ExecuteReader();
  25.             // Create SqlBulkCopy
  26.             SqlBulkCopy bulkData = new SqlBulkCopy(destinationConnector);
  27.             // Set destination table name
  28.             bulkData.DestinationTableName = tableName;
  29.             // Write data
  30.             bulkData.WriteToServer(reader);
  31.             // Close objects
  32.             bulkData.Close();
  33.             destinationConnector.Close();
  34.             mySqlConn.Close();
  35.         }
复制代码
4. 最后执行同步函数:
  1. private void SyncDB_Click(object sender, EventArgs e)
  2.         {
  3.             string server = "localhost";
  4.             string dbname = "pinkCRM";
  5.             string uid = "sa";
  6.             string password = "password";
  7.             string server2 = "server2";
  8.             string dbname2 = "pinkCRM2";
  9.             string uid2 = "sa";
  10.             string password2 = "password2";
  11.             try
  12.             {
  13.                 LogView.Text = "DB data is syncing!";
  14.                 DBUtility db = new DBUtility(server, dbname, uid, password);
  15.                 DataSet ds = db.ExecuteDS("SELECT sobjects.name FROM sysobjects sobjects WHERE sobjects.xtype = 'U'");
  16.                 DataRowCollection drc = ds.Tables[0].Rows;
  17.                 foreach (DataRow dr in drc)
  18.                 {
  19.                     string tableName = dr[0].ToString();
  20.                     LogView.Text = LogView.Text + Environment.NewLine + " syncing table:" + tableName + Environment.NewLine;
  21.                     DataSet ds2 = db.ExecuteDS("SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo." + tableName + "')");
  22.                     DataRowCollection drc2 = ds2.Tables[0].Rows;
  23.                     string primaryKeyName = drc2[0]["name"].ToString();
  24.                     db.BulkCopyTo(server2, dbname2, uid2, password2, tableName, primaryKeyName);
  25.                   
  26.                     LogView.Text = LogView.Text +"Done sync data for table:"+ tableName+ Environment.NewLine;
  27.                 }
  28.                 MessageBox.Show("Done sync db data successfully!");
  29.             }
  30.             catch (Exception exc)
  31.             {
  32.                 MessageBox.Show(exc.ToString());
  33.             }
  34.         }
复制代码

注: 这里只写了对已有数据的不再插入数据,可以再提高为如果有数据更新,可以进行更新,那么一个数据库同步工具就可以完成了!





您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

 
 
大数据行业交流
大数据行业交流
大数据求职招聘
大数据求职招聘
站长电话:
15010106923
微信联系:
hb-0310
站长邮箱:
ab12-120@163.com
大数据中国微信

QQ   

版权所有: Discuz! © 2001-2013 大数据.

GMT+8, 2024-4-29 05:07 , Processed in 0.067113 second(s), 24 queries .

快速回复 返回顶部 返回列表