1. 程式人生 > >同步數據

同步數據

length cross hit 最大化 raw 連接字符串 tabindex pop base

C/S同步數據篇


TODO:

關於同步數據篇:主要解說理清業務思路,下一篇:同步數據(根據業務需求):【將數據庫中sys_Menu數據加入到sys_Menu_Copy】

TODO:

1,表【sys_Menu_Copy】已存在數據。過濾

2,表【sys_Menu_Copy】未存在數據。加入

解說篇:1。窗口設計器生成的代碼2,後臺cs代碼:

窗口設計器生成的代碼

namespace DataSynchronousBWokerUI
{
    partial class MainForm
    {
        /// <summary>
        /// 必需的設計器變量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理全部正在使用的資源。

/// </summary> /// <param name="disposing">假設應釋放托管資源,為 true;否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗口設計器生成的代碼 /// <summary> /// 設計器支持所需的方法 - 不要 /// 使用代碼編輯器改動此方法的內容。

/// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.label = new System.Windows.Forms.Label(); this.btStop = new System.Windows.Forms.Button(); this.btStart = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.listBox1 = new System.Windows.Forms.ListBox(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // label // this.label.AutoSize = true; this.label.Location = new System.Drawing.Point(170, 67); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(0, 12); this.label.TabIndex = 13; // // btStop // this.btStop.Anchor = System.Windows.Forms.AnchorStyles.None; this.btStop.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btStop.BackgroundImage"))); this.btStop.Font = new System.Drawing.Font("宋體", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btStop.Location = new System.Drawing.Point(212, 53); this.btStop.Name = "btStop"; this.btStop.Size = new System.Drawing.Size(203, 44); this.btStop.TabIndex = 12; this.btStop.Text = "取消同步"; this.btStop.Click += new System.EventHandler(this.btStop_Click); // // btStart // this.btStart.Anchor = System.Windows.Forms.AnchorStyles.None; this.btStart.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btStart.BackgroundImage"))); this.btStart.Font = new System.Drawing.Font("宋體", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btStart.Location = new System.Drawing.Point(3, 53); this.btStart.Name = "btStart"; this.btStart.Size = new System.Drawing.Size(203, 44); this.btStart.TabIndex = 11; this.btStart.Text = "同步數據"; this.btStart.Click += new System.EventHandler(this.btStart_Click); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(33, 143); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(0, 12); this.label4.TabIndex = 14; // // label5 // this.label5.AutoSize = true; this.label5.Image = ((System.Drawing.Image)(resources.GetObject("label5.Image"))); this.label5.Location = new System.Drawing.Point(122, 142); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(0, 12); this.label5.TabIndex = 15; // // label6 // this.label6.AutoSize = true; this.label6.Image = ((System.Drawing.Image)(resources.GetObject("label6.Image"))); this.label6.Location = new System.Drawing.Point(209, 142); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(0, 12); this.label6.TabIndex = 16; // // listBox1 // this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listBox1.BackColor = System.Drawing.Color.White; this.listBox1.ForeColor = System.Drawing.SystemColors.InactiveCaptionText; this.listBox1.FormattingEnabled = true; this.listBox1.ItemHeight = 12; this.listBox1.Location = new System.Drawing.Point(1, 57); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(417, 184); this.listBox1.TabIndex = 17; // // progressBar1 // this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar1.Location = new System.Drawing.Point(1, 12); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(417, 30); this.progressBar1.TabIndex = 18; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.btStart, 0, 1); this.tableLayoutPanel1.Controls.Add(this.btStop, 1, 1); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 243); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 2; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(419, 100); this.tableLayoutPanel1.TabIndex = 19; // // MainForm // this.BackgroundImage = global::DataSynchronousBWokerUI.Properties.Resources._1234564578798798798797987987987987; this.ClientSize = new System.Drawing.Size(419, 343); this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.progressBar1); this.Controls.Add(this.listBox1); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "測試:同步數據"; this.tableLayoutPanel1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label; private System.Windows.Forms.Button btStop; private System.Windows.Forms.Button btStart; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; } }

後臺cs代碼

定義線程名。線程開始標識,連接server成功標識,退出程序標識。源數據庫。目標數據庫

private Thread preg;//線程名
        private bool tureOfalse;//線程運行標識
        public bool conYes;//連接服務成功失敗標識
        private bool one = false;//退出程序標識
        string strdbHipis = System.Configuration.ConfigurationManager.AppSettings["NewHmFrameWork_QHS_SQ"].ToString();//源數據庫
        //string strdbPreg = System.Configuration.ConfigurationManager.AppSettings["NewHmFrameWork_QHS_SQ_QingHai"].ToString();//目標數據庫
        string strdbPreg = System.Configuration.ConfigurationManager.ConnectionStrings["NewHmFrameWork_QHS_SQ"].ToString();//目標數據庫

主方法實行調用:

public MainForm()
        {
            InitializeComponent();
            btStop.Enabled = false;//未開啟進程,不同意取消進程
            //托付
            InitTrayIcon();//圖標托盤托付
            Control.CheckForIllegalCrossThreadCalls = false;//線程托付
            this.FormClosing += new FormClosingEventHandler(form_Closing);//退出程序托付
        }

圖標聲明

//圖標聲明
        NotifyIcon trayIcon = new NotifyIcon();
        //圖標路徑C:\Users\Administrator\Desktop\DataSynchronousBWokerUI\DataSynchronousBWokerUI\Images\_net_32.ico
        private Icon mNetTrayIcon = new Icon("..//Images//_net_32.ico");

線程開始

//線程開始
        private void btStart_Click(object sender, EventArgs e)
        {
            tureOfalse = true;
            preg = new Thread(new ThreadStart(PREG));
            preg.Start();

            btStart.Enabled = false;
            btStop.Enabled = true;
        }

線程方法

//線程方法
        private void PREG()
        {
            do
            {
                listBox1.Items.Add("正在連接源數據庫... ...!");
                listBox1.Items.Add("正在連接目標數據庫... ...!");
                ISopenCon();
            } while (!conYes);
            DoWork_select();
        }

線程停止

//線程停止
        private void btStop_Click(object sender, EventArgs e)
        {
            tureOfalse = false;
            preg.Abort();
            /*2015/2/2 調整:點擊[取消同步]。清空listbox當前數據*/
            this.listBox1.Items.Clear();
            listBox1.Items.Add("待同步... ...");
            //控件顯示隱藏

            btStart.Enabled = true;
            btStop.Enabled = false;
        }

連接目標數據庫失敗將信息寫入LOG

/// <summary>
        /// 連接目標數據庫失敗將信息寫入LOG
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fslog(Exception ex)
        {
            string filepath = DateTime.Now.ToString("yyyyMMdd") + ".log";
            FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            DateTime time = DateTime.Now;
            sw.WriteLine(time);
            //sw.WriteLine("連接目標數據庫失敗");
            sw.WriteLine(ex.Message);
            sw.WriteLine("---------------------------------------------------------");
            sw.Close();
            fs.Close();
        }

嘗試連接源、目標數據庫

/// <summary>
        /// 嘗試連接源、目標數據庫
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ISopenCon()
        {

            try
            {
                SqlConnection conhipis = new SqlConnection(strdbHipis);
                conhipis.Open();
                conYes = true;
                conhipis.Close();
                SqlConnection conPreg = new SqlConnection(strdbPreg);
                conPreg.Open();
                conYes = true;
                conPreg.Close();

            }
            catch (Exception ex)
            {
                conYes = false;
                fslog(ex);
                listBox1.Items.Add("連接數據庫失敗......");
                Thread.Sleep(60000);
            }

        }

嘗試刪除目標數據庫

/// <summary>
        /// 嘗試刪除目標數據庫
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelPreg()
        {

            //try
            //{
            //bool delResult = true;
            ////插入數據之前。先刪除當前社區的已有數據
            //string strDelSQL = "delete from dbo.sys_Menu ";
            //strDelSQL += "delete from dbo.sys_MenuInRoles ";
            //strDelSQL += "delete from dbo.sys_UsersInRoles ";
            //delResult = ExecuteSql(strDelSQL);
            //if (delResult == false)
            //{
            //    //this.label4.Text = "刪除目標數據庫失敗......";
            //    listBox1.Items.Add("刪除目標數據庫失敗......");
            //}
            //else
            //{
            //    //this.label4.Text = "刪除目標數據庫成功......";
            //    listBox1.Items.Add("刪除目標數據庫成功......");
            //}


            /*測試數據:刪除dbo.sys_Menu_Copy在測試期間錄入的數據便於二次錄入<多次錄入>*/
            SqlConnection hipiscon;
            SqlCommand SQLcom;
            hipiscon = new SqlConnection(strdbHipis);
            string strDelSQL = "delete from dbo.sys_Menu_Copy ";
            SQLcom = new SqlCommand(strDelSQL, hipiscon);
            try
            {
                hipiscon.Open();
                SQLcom.ExecuteNonQuery();
                hipiscon.Close();
                listBox1.Items.Add("刪除目標數據庫成功......");
            }
            catch (Exception ex)
            {
                listBox1.Items.Add("刪除目標數據庫失敗......");
                fslog(ex);
                //Thread.Sleep(300000);
            }
            //}
            //catch (Exception ex)
            //{
            //    conYes = false;
            //    fslog(ex);
            //    listBox1.Items.Add("刪除目標數據庫失敗......");
            //    Thread.Sleep(60000);
            //}
        }

對源庫操作。對目標庫操作

/// <summary>
        /// 對源庫操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private DataTable IsOpenDT(string strSQL, string strConn)
        {
            SqlConnection hipiscon;
            SqlCommand SQLcom;
            DataTable DT;
            SqlDataAdapter SQLADA;
            hipiscon = new SqlConnection(strConn);
            SQLcom = new SqlCommand(strSQL, hipiscon);
            try
            {
                hipiscon.Open();
                SQLcom.ExecuteNonQuery();
                conYes = true;
                hipiscon.Close();
            }
            catch (Exception ex)
            {
                conYes = false;
                fslog(ex);
                //Thread.Sleep(300000);
            }
            DT = new DataTable();
            SQLADA = new SqlDataAdapter(SQLcom);
            SQLADA.Fill(DT);
            return DT;
        }
        /// <summary>
        /// 對目標庫操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IsOpen(string strsql, string strconn)
        {
            try
            {
                SqlConnection pregcon = new SqlConnection(strconn);
                SqlCommand sqlcom = new SqlCommand(strsql, pregcon);
                pregcon.Open();
                sqlcom.ExecuteNonQuery();
                conYes = true;
                pregcon.Close();

            }
            catch (Exception ex)
            {
                conYes = false;
                fslog(ex);
                //Thread.Sleep(300000);
            }
        }

詳細操作方法

/// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sender"></param>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DoWork_select()
        {

            //string strtb = System.Configuration.ConfigurationManager.AppSettings["strtable"].ToString();
            //string strupdt = System.Configuration.ConfigurationManager.AppSettings["updt"].ToString();
            //string strwhere = System.Configuration.ConfigurationManager.AppSettings["where"].ToString();


            while (tureOfalse)
            {
                ISopenCon();
                /*2015/2/2 調整:不能把菜單所有刪除,沒有的加入到server上去,已存在的過濾掉*/
                //DelPreg();
                //DataTable dt = IsOpenDT(strSQL, strdbHipis);

                //String[] tablenamekey = new String[3] { "dbo.sys_Menu", "dbo.sys_MenuInRoles", "dbo.sys_UsersInRoles" };//源數據庫
                //String[] tablenamekeypreg = new String[3] { "dbo.sys_Menu_Copy", "dbo.sys_MenuInRoles_Copy", "dbo.sys_UsersInRoles_Copy" };//目標數據庫

                //測試數據
                String[] tablenamekey = new String[1] { "dbo.sys_Menu" };//源數據庫
                String[] tablenamekeypreg = new String[1] { "dbo.sys_Menu_Copy" };//目標數據庫
                if (tablenamekey.Length > 0)
                {
                    for (int i = 0; i < tablenamekey.Length; i++)
                    {
                        string strtablenamekey = tablenamekey[i];
                        string strSQL1 = "select * from ";
                        strSQL1 += strtablenamekey;
                        strSQL1 += " where (1=1)";

                        insert_OR_update(strdbHipis, ref strSQL1, tablenamekeypreg[i]);
                    }
                }
            }
        }

        /// <summary>
        /// 插入,更新 最新數據到PIS數據庫
        /// </summary>
        /// <param name="con">須要更新的表的連接字符串</param>
        /// <param name="lastSQL">最後SQL語句</param>
        /// <param name="tbName">須要操作的表</param>
        private void insert_OR_update(string strdbHipis, ref string strSQL, string tbName)
        {
            int a = 0;
            int b = 0;
            string lastSQL;
            DataTable dttb;
            DataTable dttb1;
            dttb = IsOpenDT(strSQL, strdbHipis);

            /*2015/2/2 調整:新增[進度條]追加顯示載入信息*/
            progressBar1.Maximum = dttb.Rows.Count;//設置最大長度值
            progressBar1.Value = 0;//設置當前值
            progressBar1.Step = 1;//設置每次增長1條數據

            listBox1.Items.Add("連接源數據庫成功......");
            listBox1.Items.Add("連接目標數據庫成功......");
            listBox1.Items.Add("正在同步... ...");
            try
            {
                for (int i = 0; i < dttb.Rows.Count; i++)//依據推斷條件循環更新數據庫中的信息
                {
                    /*2015/2/2 調整:不能把菜單所有刪除,沒有的加入到server上去,已存在的過濾掉*/
                    lastSQL = "select * from " + tbName + " where sCode= '" + dttb.Rows[i][0].ToString().Trim() + "'";
                    //更新dttb1:一條記錄 推斷是否存在<過濾:新增>
                    /*測試數據庫:源庫和目標庫一致 後期調整目標庫連接字符串*/
                    dttb1 = IsOpenDT(lastSQL, strdbPreg);
                    //目標庫中存在一條數據 取消
                    if (dttb1 != null && dttb1.Rows.Count > 0)
                    {
                        a = a + 1;
                        listBox1.Items.Add("已過濾" + a.ToString() + "條。");
                    }
                    else
                    {
                        string valuse = "";
                        string allcolumName = "";
                        for (int j = 0; j < dttb1.Columns.Count; j++)
                        {
                            if (j == dttb1.Columns.Count - 1)
                            {
                                allcolumName += dttb1.Columns[j].ColumnName.ToString();
                            }
                            else
                            {
                                allcolumName += dttb1.Columns[j].ColumnName.ToString() + ",";
                            }
                        }

                        //假設在線庫中的時間為空則進行插入操作


                        for (int j = 0; j < dttb.Columns.Count; j++)
                        {
                            if (j == dttb.Columns.Count - 1)
                            {
                                valuse += "'" + dttb.Rows[i][j].ToString() + "'";
                            }
                            else
                            {
                                valuse += "'" + dttb.Rows[i][j] + "',";
                            }
                        }

                        lastSQL = "insert into " + tbName + " (" + allcolumName + ") values (" + valuse + ")";

                        IsOpen(lastSQL, strdbPreg);
                        b = b + 1;
                        listBox1.Items.Add("已插入" + b.ToString() + "條!");
                    }
                    /*2015/2/2 調整:新增[進度條]追加顯示載入信息*/
                    progressBar1.Value += progressBar1.Step;//讓進度條添加一次
                }
            }
            catch (Exception ex)
            {
                fslog(ex);
            }
            if ((a + b) > 0)
            {
                listBox1.Items.Add(tbName + "成功過濾" + a + "條數據條數據,成功插入" + b + "條數據。");
                listBox1.Items.Add(tbName + "同步數據成功。");
                //tureOfalse = false;
                preg.Abort();//線程運行標識:同步成功 關閉線程
                //UPINlog(a, b, tbName);
            }
            else
            {
                listBox1.Items.Add("");
            }

        }

此段代碼相當於sqlhelper.cs功能【連接數據庫】

/// <summary>
        /// 運行SQL語句
        /// </summary>
        /// <param name="SQLString">SQL語句</param>
        /// <returns>bool值,成功返回true,失敗返回false</returns>
        public static bool ExecuteSql(string SQLString)
        {
            bool isSucc = false;
            using (SqlConnection connection = new SqlConnection("Data Source=192.168.44.161;Initial Catalog=NewHmFrameWork_QHS_SQ_QingHai;Persist Security Info=True;User ID=sa;Password=jqkj123$%^;"))
            {
                connection.Open();

                using (SqlTransaction trans = connection.BeginTransaction())
                {
                    using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                    {

                        cmd.Transaction = trans;
                        int rows = cmd.ExecuteNonQuery();
                        trans.Commit();
                        isSucc = true;


                    }
                }

            }
            return isSucc;
        }

初始化托盤圖標

/// <summary>
        /// 初始化托盤圖標
        /// </summary>
        public void InitTrayIcon()
        {

            // 設置托盤圖標的菜單
            trayIcon.Icon = mNetTrayIcon;
            trayIcon.Text = "單擊最大化程序";
            trayIcon.Visible = true;
            trayIcon.Click += new EventHandler(trayIcon_Click);
            MenuItem[] mnuItems = new MenuItem[4];
            mnuItems[0] = new MenuItem();
            mnuItems[0].Text = "顯示";
            mnuItems[0].Click += new EventHandler(Item0_Click);

            mnuItems[1] = new MenuItem();
            mnuItems[1].Text = "隱藏";
            mnuItems[1].Click += new EventHandler(Item1_Click);

            mnuItems[2] = new MenuItem("-");

            mnuItems[3] = new MenuItem();
            mnuItems[3].Text = "退出程序";
            mnuItems[3].Click += new EventHandler(Item3_Click);
            trayIcon.ContextMenu = new ContextMenu(mnuItems);
        }

顯示窗口,隱藏窗口。退出事件,點擊托盤圖標,單擊X退出程序

/// <summary>
        /// 顯示窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Item0_Click(object sender, EventArgs e)
        {
            this.Show();

        }

        /// <summary>
        /// 隱藏窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Item1_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.trayIcon.ShowBalloonTip(5, "提示", "單擊最大化程序", ToolTipIcon.Info);
        }

        /// <summary>
        /// 退出事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Item3_Click(object sender, EventArgs e)
        {

            preg.Abort();
            Application.Exit();
        }

        /// <summary>
        /// 點擊托盤圖標
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void trayIcon_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Maximized;

        }
        /// <summary>
        /// 單擊X退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void form_Closing(object sender, FormClosingEventArgs e)
        {
            if (one == false)
            {
                DialogResult dia = MessageBox.Show("是否真的退出程序!", " ", MessageBoxButtons.OKCancel);
                if (dia == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    this.Show();
                    this.trayIcon.Visible = true;
                }
                if (dia == DialogResult.OK)
                {
                    one = true;
                    /*2015/2/2 調整:退出[未同步時。直接退出]*/
                    preg = new Thread(new ThreadStart(PREG));
                    preg.Start();
                    preg.Abort();
                    Application.Exit();
                }
            }
        }


效果圖

技術分享技術分享技術分享技術分享技術分享技術分享


同步數據