using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace Lskj_SynchronizeData { public partial class FrMain : Form { public string Connection1 = "QkYyNjE3QTcxQjc4RDFFMDlERjlFMDc1QkIyMDVGRjdDRUIyMEVEOUM5NjBCQjc5NTA5NzdEQTk0MkNEQTE1RTFGMEIwMThFNUJDQTE0RjE1NjQwM0U5QTYxMThCMDY2MTA4NkE2OTIxNTNBQjQ0MjRDMDIwM0Q5OEVDQjkwQTVCN0RENjJBODkxNUNGOUM5OEI5RTEzN0E3ODBERjg2OURCNEQ5QTlCMzhCQUZGQ0FBNUREMjY4M0FCODg2RTkxMDRERTQ3MjRGQTE1MERDOTJGRDFDRjY2REQ1ODYyREUzN0RGM0ZBQzc4NzJENjIwNDg4RUUyNkI3ODE1RjlDM0I0MjNCQzcyOENDN0VDMTg0QUU0MjgwMDVDMENBOUZF"; /// /// 远程数据库名 /// public string DataBase = "lskj_weixin"; /// /// 远程服务器名 /// private string serverName = "114.116.152.217,14331"; /// /// 本地数据库名 /// private string localDBName; /// /// 本地服务器名 /// private string localServer; /// /// 数据库远程连接字符串 /// string connStr; /// /// 数据库本地连接字符串 /// string localconnStr; private System.Timers.Timer timer = new System.Timers.Timer(); private DataTable localDt; public FrMain() { InitializeComponent(); } /// /// 说明:初始化 /// 创建人:钱雄 /// 创建日期:2020-11-07 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The item. protected override void OnLoad(EventArgs e) { //设置timer timer.Interval = 1000*60; //设置是否重复计时,如果该属性设为False,则只执行timer_Elapsed方法一次。 timer.AutoReset = true; timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); bool localConn = DBConfig.Instance.CreateConnection(); bool romoteConn = CreateConnection(); } #region 事件相关 /// /// 说明:开始按钮点击 /// 创建人:钱雄 /// 创建日期:2020-11-27 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. private void OnStartClick(object sender, EventArgs e) { timer.Enabled = true; this.txt_log.Text = ""; RefreshLog(DateTime.Now + ":定时器启动中,请稍后\r\n"); } /// /// 显示信息设置 /// /// public void RefreshLog(string msg) { Invoke((EventHandler)delegate { this.txt_log.Text += msg; this.txt_log.Focus();//获取焦点 this.txt_log.Select(this.txt_log.TextLength, 0);//光标定位到文本最后 this.txt_log.ScrollToCaret();//滚动到光标处 }); } /// /// 说明:暂停按钮点击 /// 创建人:钱雄 /// 创建日期:2020-11-27 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. private void OnSuspendClick(object sender, EventArgs e) { timer.Enabled = false; } /// /// 说明:初始化表按钮点击 /// 创建人:钱雄 /// 创建日期:2020-11-27 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. private void OnInitTable(object sender, EventArgs e) { string createSql; if (DBConfig.Instance.CreateConnection()) { localconnStr = DBConfig.Instance.GetConnection(); string sqlValue = string.Format("select count(1) as result from sys.objects where name = 'P_SystemMSGSendTab'"); string sqlValue1 = string.Format("select count(1) as result from sys.objects where name = 'P_SystemMSGSendListTab'"); try { if (SqlHelper.ExecuteDataTable(sqlValue).Rows[0]["result"] + "" != "1") { createSql = "CREATE TABLE P_SystemMSGSendTab(id int IDENTITY(1,1) NOT NULL,msgID bigint NULL,ClientCode varchar(50) NULL,OpenID varchar(50) NULL,MsgInfo varchar(500) NULL,MsgLink varchar(max) NULL,CreateTime datetime NULL,SendTime datetime NULL,SendStatus int NULL,StatusMsg varchar(150) NULL,msgType varchar(50) NULL,msg_first varchar(500) NULL,msg_keyword1 [varchar](300) NULL,msg_keyword2 varchar(300) NULL,msg_keyword3 varchar(300) NULL,msg_keyword4 varchar(300) NULL, msg_keyword5 varchar(300) NULL,msg_remark varchar(500) NULL,isSync int NULL, PRIMARY KEY CLUSTERED (id ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]"; if (SqlHelper.ExecuteNonQuery(createSql) > 0) { MessageBox.Show("表P_SystemMSGSendTab创建成功"); } } if (SqlHelper.ExecuteDataTable(sqlValue1).Rows[0]["result"] + "" != "1") { createSql = "CREATE TABLE P_SystemMSGSendListTab(id int IDENTITY(1,1) NOT NULL,msgID bigint NULL,ClientCode varchar(50) NULL,OpenID varchar(50) NULL,MsgInfo varchar(500) NULL,MsgLink varchar(max) NULL,CreateTime datetime NULL,SendTime datetime NULL,SendStatus int NULL,StatusMsg varchar(150) NULL,msgType varchar(50) NULL,msg_first varchar(500) NULL,msg_keyword1 [varchar](300) NULL,msg_keyword2 varchar(300) NULL,msg_keyword3 varchar(300) NULL,msg_keyword4 varchar(300) NULL, msg_keyword5 varchar(300) NULL,msg_remark varchar(500) NULL,isSync int NULL, PRIMARY KEY CLUSTERED (id ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]"; if (SqlHelper.ExecuteNonQuery(createSql) > 0) { MessageBox.Show("表P_SystemMSGSendListTab创建成功"); } } } catch(Exception ex) { MessageBox.Show(ex.Message); } } } /// /// 说明:定时器事件 /// 创建人:钱雄 /// 创建日期:2020-11-27 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (this.txt_log.Lines.Count() > 1000) { this.txt_log.Text = ""; } SynchronizeData(); timer.Enabled = true; } #endregion /// /// 说明:同步数据 /// 创建人:钱雄 /// 创建日期:2020-11-27 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. private void SynchronizeData() { timer.Enabled = false; string sqlValue = string.Empty; string result = string.Empty; RefreshLog(DateTime.Now + ":准备插入数据\r\n"); //本地数据库连接 try { if (DBConfig.Instance.CreateConnection()) { //MessageBox.Show("本地数据库连接成功"); localDBName = DBConfig.Instance.DataBase; localServer = DBConfig.Instance.ServerName; localconnStr = DBConfig.Instance.GetConnection(); sqlValue = string.Format("select count(1) as result from sys.objects where name = 'P_SystemMSGSendTab'"); result = SqlHelper.ExecuteDataTable(sqlValue).Rows[0]["result"] + ""; if (result == "1") { //判断字段是否存在 string existSql = "select count(1) as result from syscolumns where id=object_id('P_SystemMSGSendTab') and name='isSync'"; result = SqlHelper.ExecuteDataTable(existSql).Rows[0]["result"] + ""; if (result != "1") { string alterSql = "alter table P_SystemMSGSendTab add isSync bit not null default 0"; SqlHelper.ExecuteNonQuery(alterSql); } localDt = SqlHelper.ExecuteDataTable("select * from P_SystemMSGSendTab where isSync=0"); } else { RefreshLog(DateTime.Now + ":当前数据库没有对应表\r\n"); timer.Enabled = false; } } } catch(Exception e) { MessageBox.Show(e.Message); } try { //远程数据库连接 if (CreateConnection()) { sqlValue = string.Format("select count(1) as result from sys.objects where name = 'P_SystemMSGSendTab'"); result = SqlHelper.ExecuteDataTable(sqlValue).Rows[0]["result"] + ""; if (result == "1" && localDt.Rows.Count > 0) { //RefreshLog(DateTime.Now + ":数据插入中\r\n"); WriteDataToDB(localDt, "P_SystemMSGSendTab"); } else { RefreshLog(DateTime.Now + ":没有要插入的数据\r\n"); } } else { RefreshLog(DateTime.Now + ":远程数据库连接失败\r\n"); } //timer.Enabled = true; } catch(Exception ex) { MessageBox.Show(ex.Message); } } /// /// 说明:创建数据库连接 /// 创建人:钱雄 /// 创建日期:2020-11-27 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// true if XXXX, false otherwise. public bool CreateConnection() { connStr = GetConnection(); if (SqlHelper._connection != null) { try { SqlHelper._connection.Close(); SqlHelper._connection.Dispose(); } catch (Exception) { } SqlHelper._connection = null; } try { SqlHelper._connection = new SqlConnection(connStr); SqlHelper._connection.Open(); return true; } catch (Exception ex) { MessageBox.Show(ex.Message); } return false; } /// /// 说明:获取C#连接字符串 /// 创建人:龚宇超 /// 创建日期:2017-08-07 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// System.String. public string GetConnection() { return string.Format(AESUtil.Decrypt(Connection1), serverName, DataBase); } /// /// 将DataTable中数据写入数据库中 /// /// /// public bool WriteDataToDB(DataTable dt, string tableName) { if (dt == null || dt.Rows.Count == 0) { return true; } string colNames = ""; for (int i = 0; i < dt.Columns.Count; i++) { if ((i == 0) || (i == dt.Columns.Count - 1)) continue; colNames += dt.Columns[i].ColumnName + ","; } colNames = colNames.TrimEnd(','); string cmd = ""; string colValues; int count = 0; string ids = string.Empty; //string cmdmode = string.Format("insert into {0}({1}) values({{0}});", tableName, colNames); string cmdmode = string.Format("insert into OPENDATASOURCE('SQLOLEDB','{0}').{1}.dbo.{2} ({3}) values({{0}});", connStr, DataBase, tableName, colNames); for (int i = 0; i < dt.Rows.Count; i++) { ids += dt.Rows[i][0] + ","; //bool isSync; colValues = ""; //isSync = string.IsNullOrEmpty(dt.Rows[i][dt.Columns.Count - 1] + "") ? false : Convert.ToBoolean(dt.Rows[i][dt.Columns.Count - 1]); //if (!isSync) { for (int j = 0; j < dt.Columns.Count; j++) { count++; if (j == 0 || j == dt.Columns.Count - 1) continue; if (dt.Rows[i][j].GetType() == typeof(DBNull)) { colValues += "NULL,"; continue; } if (dt.Columns[j].DataType == typeof(string)) colValues += string.Format("'{0}',", dt.Rows[i][j]); else if (dt.Columns[j].DataType == typeof(int) || dt.Columns[j].DataType == typeof(float) || dt.Columns[j].DataType == typeof(double)) { colValues += string.Format("{0},", dt.Rows[i][j]); } else if (dt.Columns[j].DataType == typeof(DateTime)) { colValues += string.Format("cast('{0}' as datetime),", dt.Rows[i][j]); } else if (dt.Columns[j].DataType == typeof(bool)) { colValues += string.Format("{0},", dt.Rows[i][j].ToString()); } else colValues += string.Format("'{0}',", dt.Rows[i][j]); } cmd += string.Format(cmdmode, colValues.TrimEnd(',')); //count++; //} } int ret = 0; try { if (count > 0) { RefreshLog(DateTime.Now + ":数据插入中\r\n"); ret = SqlHelper.ExecuteNonQuery(cmd); RefreshLog(DateTime.Now + ":成功插入" + ret + "条数据\r\n"); } } catch (Exception e) { //写错误日志... string strOuput = string.Format("向数据库中写数据失败,错误信息:{0},异常{1}\n", e.Message, e.InnerException); RefreshLog(DateTime.Now + strOuput + "\r\n"); } if (ret == -1) { return false; } ids = ids.TrimEnd(','); if (count == 0) { RefreshLog(DateTime.Now + "没有要插入的数据\r\n"); } try { string updateValue = string.Format("Update OPENDATASOURCE('SQLOLEDB','{0}').{1}.dbo.P_SystemMSGSendTab set isSync=1 where id in ({2})", localconnStr, localDBName, ids); if (DBConfig.Instance.CreateConnection()&&SqlHelper.ExecuteNonQuery(updateValue) > 0) { RefreshLog(DateTime.Now + ":本地表字段isSync修改成功\r\n"); } } catch(Exception e) { RefreshLog(DateTime.Now + ":" + e.Message+"\r\n"); } return true; } } }