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();
}
}
}
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;
}
}
}
}
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#同步SQL Server数据库中的数据--数据库同步工具[同步新数据]的更多相关文章
- SQL Server 2016中In-Memory OLTP继CTP3之后的新改进
SQL Server 2016中In-Memory OLTP继CTP3之后的新改进 转译自:https://blogs.msdn.microsoft.com/sqlserverstorageengin ...
- SQL Server 2012中快速插入批量数据的示例及疑惑
SQL Server 2008中SQL应用系列--目录索引 今天在做一个案例演示时,在SQL Server 2012中使用Insert语句插入1万条数据,结果遇到了一个奇怪的现象,现将过程分享出来,以 ...
- SQL Server 2005 中的分区表和索引
SQL Server 2005 中的分区表和索引 SQL Server 2005 69(共 83)对本文的评价是有帮助 - 评价此主题 发布日期 : 3/24/2005 | 更新 ...
- SQL Server 2005中设置Reporting Services发布web报表的匿名访问
原文:SQL Server 2005中设置Reporting Services发布web报表的匿名访问 一位朋友提出个问题:集成到SQL Server 2005中的Reporting Services ...
- SQL Server 2008中的MERGE(数据同步)
OK,就像标题呈现的一样,SQL Server 2008中的MERGE语句能做很多事情,它的功能是根据源表对目标表执行插入.更新或删除操作.最典型的应用就是进行两个表的同步. 下面通过一个简单示例来演 ...
- 【SQL Server高可用性】数据库复制:SQL Server 2008R2中通过数据库复制,把A表的数据复制到B表
原文:[SQL Server高可用性]数据库复制:SQL Server 2008R2中通过数据库复制,把A表的数据复制到B表 经常在论坛中看到有人问数据同步的技术,如果只是同步少量的表,那么可以考虑使 ...
- SQL Server 2008中新增的 1.变更数据捕获(CDC) 和 2.更改跟踪
概述 1.变更数据捕获(CDC) 每一次的数据操作都会记录下来 2.更改跟踪 只会记录最新一条记录 以上两种的区别: http://blog.csdn.n ...
- SQL Server 2008中新增的变更数据捕获(CDC)和更改跟踪
来源:http://www.cnblogs.com/downmoon/archive/2012/04/10/2439462.html 本文主要介绍SQL Server中记录数据变更的四个方法:触发器 ...
- SQL Server 执行计划利用统计信息对数据行的预估原理以及SQL Server 2014中预估策略的改变
前提 本文仅讨论SQL Server查询时, 对于非复合统计信息,也即每个字段的统计信息只包含当前列的数据分布的情况下, 在用多个字段进行组合查询的时候,如何根据统计信息去预估行数的. 利用不同字段 ...
随机推荐
- Android中Drawable分类汇总(上)
Android把可绘制的对象抽象为Drawable,不同的图形图像资源就代表着不同的drawable类型.Android FrameWork提供了一些具体的Drawable实现,通常在代码中都不会直接 ...
- Android bitmap序列化
最近在开发中需要用到图片bitmap的序列化并进行传递,发现bitmap是没有序列化的,下面是自己实现的一个序列化方法,分享下. 以下是通过byte[]来进行序列化的,因为bitmap是没有序列化的, ...
- opengl学习笔记(二)
这段时间终于接触到一点点shader了,应该说shader是非常有用的东西吧,它就是能够把一些固定渲染管线的东西改变了,按照自己的意愿进行渲染,这样的话图形就可以自由发挥了. 我也只是试验了一下sha ...
- perl学习(10) 字符串处理函数和排序
1.1.index Perl 查找子串第一次在大字符串中出现的地方,返回第一个字符的位置. . . my $stuff = “Howordy world!”; my $where3 = index($ ...
- Bootstrap3学习笔记
Bootstrap3简单介绍----专题1 声明:本文章是给初学bootstrap3的同学添加记忆的, 一定有非常多欠缺和不完好的地方, 希望能帮助到大家, 也希望能让很多其它的人了解boostrap ...
- poj 3266 Cow School 分数规划
这个题目难度非常大,首先对于老师的一种方案,应用分数规划的一般做法,求出所有的c=t-rate*p,如果没有选择的c值中的最大值比选择了的c值中的最小值大,那么这个解是可以改进的. 那么问题就转化成了 ...
- 操作系统栈溢出检測之ucosII篇
操作系统栈溢出检測之uc/osII篇 Author : David Lin (林鹏) E-mail : linpeng1 ...
- hdu 3350
hdu 3350 题意:让你求运算式的结果和运算过程中加法的次数 (a) > (b) ? (a) : (b) 大于取a,小于等于取b MAX( 1 + 2 , 3) 因为(a) > (b) ...
- 从svn下载项目后build path为灰色
今天从svn上下载项目后,想加入下面jar包.可是build path为灰色. 解决的方法是:1.在项目上右键properties---project facts 如图所看到的: 点击右側conver ...
- 刚開始学习的人制作VMOS场效应管小功放
VMOS场效应管既有电子管的长处又有晶体管的长处,用它制作的功率放大器声音醇厚.甜美,动态范围大.频率响应好.因此近年来在音响设备中得到了广泛应用. 大功率的场效应管功率放大器.电.路比較复杂.制作和 ...