1. 程式人生 > >c#寫的sql Server資料庫自動備份程式

c#寫的sql Server資料庫自動備份程式

這幾天寫了一個xp下安裝sql Server 2005 express版本的資料庫自動備份程式,大家看看若是有覺得不合理的地方歡迎指正

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using Microsoft.Win32;
using System.Diagnostics;


namespace CPU卡表資料庫備份程式
{
    public partial class Config : Form
    {
        public Config()
        {
            InitializeComponent();
        }


        private void Config_Load(object sender, EventArgs e)
        {
            //this.Cb_Hour.SelectedIndex = 0;
            //this.Cb_Minute.SelectedIndex = 0;
            string Dir_Source = GetValue("Dir");
            this.Txt_DirSource.Text = Dir_Source;
            string Hour = GetValue("Hour").Trim();
            string Minute = GetValue("Minute").Trim();
            this.Cb_Hour.Text = Hour;
            this.Cb_Minute.Text = Minute;
            string AutoRun = GetValue("AutoRun");
            if (AutoRun.Trim() == "false")
            {
                this.CheckBox_AutoRun.Checked = false;
            }
            else
            {
                this.CheckBox_AutoRun.Checked = true;
            }
        }


        private void Txt_DirSource_MouseClick(object sender, MouseEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "請選擇備份路徑";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                this.Txt_DirSource.Text = dialog.SelectedPath;
            }
            else
            {
                return;
            }
        }


        private void Btn_SetDir_Click(object sender, EventArgs e)
        {
            //首先判斷目錄是否存在
            string Dir_Source = this.Txt_DirSource.Text.Trim();
            if (Dir_Source == "" || Directory.Exists(Dir_Source) == false)
            {
                MessageBox.Show("備份目錄設定有誤,請查證", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                SetValue("Dir", Dir_Source);
                MessageBox.Show("備份目錄設定為"+Dir_Source,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
 
            }
            
        }
        /// <summary>
        /// 設定程式開機啟動
        /// 或取消開機啟動
        /// </summary>
        /// <param name="started">設定開機啟動,或者取消開機啟動</param>
        /// <param name="exeName">登錄檔中程式的名字</param>
        /// <param name="path">開機啟動的程式路徑</param>
        /// <returns>開啟或則停用是否成功</returns>
        public static bool runWhenStart(bool started, string exeName, string path)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//開啟登錄檔子項
            if (key == null)//如果該項不存在的話,則建立該子項
            {
                key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
            }
            if (started == true)
            {
                try
                {
                    key.SetValue(exeName, path);//設定為開機啟動
                    key.Close();
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                try
                {
                    key.DeleteValue(exeName);//取消開機啟動
                    key.Close();
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }
        public string GetValue(string AppKey)
        {
            XmlDocument xDoc = new XmlDocument();
            //獲取可執行檔案的路徑和名稱 
            //MessageBox.Show(Application.StartupPath);
            xDoc.Load(System.Windows.Forms.Application.StartupPath + "/" + "Config.xml");
            XmlNode xNode;
            XmlElement xElem1;
            xNode = xDoc.SelectSingleNode("Settings");
            xElem1 = (XmlElement)xNode.SelectSingleNode(AppKey);
            if (xElem1 != null)
                return xElem1.InnerText;
            else
                return "";
        }
        public void SetValue(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            //獲取可執行檔案的路徑和名稱 
            xDoc.Load(System.Windows.Forms.Application.StartupPath + "/" + "Config.xml");
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("Settings");
            xElem1 = (XmlElement)xNode.SelectSingleNode(AppKey);
            if (xElem1 != null)
                xElem1.InnerText = AppValue;
            else
            {
                xElem2 = xDoc.CreateElement(AppKey);
                xElem2.Value = AppValue;
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(Directory.GetCurrentDirectory() + "/" + "Config.xml");
        }


        private void Btn_Time_Config_Click(object sender, EventArgs e)
        {
            if (this.Cb_Hour.Text.Trim()=="")
            {
                MessageBox.Show("小時資料不能為空","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            else if (this.Cb_Minute.Text.Trim() == "")
            {
                MessageBox.Show("分鐘資料不能為空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                SetValue("Hour",this.Cb_Hour.Text.Trim());
                SetValue("Minute",this.Cb_Minute.Text.Trim());
                MessageBox.Show("備份時間配置成功","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
        }


        private void Btn_AutoRun_Click(object sender, EventArgs e)
        {
            if (this.CheckBox_AutoRun.Checked == true)
            {
                //首先修改文件
                SetValue("AutoRun", "true");
                //然後設定修改值
                if (runWhenStart(true, "AutoBackupDatabase", Directory.GetCurrentDirectory() + "/" + "CPU卡表資料庫備份程式.exe") == true)
                {
                    MessageBox.Show("備份程式設定為開機啟動", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    MessageBox.Show("程式設定開機啟動過程中發生未知錯誤請查證","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    return;
 
                }
            }
            else
            {
                SetValue("AutoRun","false");
                if (runWhenStart(true, "AutoBackupDatabase", Directory.GetCurrentDirectory() + "/" + "CPU卡表資料庫備份程式.exe") == true)
                {
                    MessageBox.Show("備份程式取消開機啟動", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    MessageBox.Show("程式取消開機啟動過程中發生未知錯誤請查證", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;


                }
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            string str5 = Application.StartupPath;
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;
using SQLDMO;
using System.IO;


namespace CPU卡表資料庫備份程式
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int Hour;
        int Minute;
        private void 關於我們ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutUs au = new AboutUs();
            au.Show();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            string DatabaseName = GetValue("DatabaseName");
            this.Txt_Database_Name.Text = DatabaseName;
            Hour = int.Parse(GetValue("Hour"));
            Minute = int.Parse(GetValue("Minute"));
            string Dir = GetValue("Dir");
            this.Txt_Dir.Text = Dir;






        }
        public string GetValue(string AppKey)
        {
            XmlDocument xDoc = new XmlDocument();
            //獲取可執行檔案的路徑和名稱
            //2012年7月20日修改程式
            //MessageBox.Show(System.Windows.Forms.Application.StartupPath);
            xDoc.Load(System.Windows.Forms.Application.StartupPath + "/" + "Config.xml");
            XmlNode xNode;
            XmlElement xElem1;
            xNode = xDoc.SelectSingleNode("Settings");
            xElem1 = (XmlElement)xNode.SelectSingleNode(AppKey);
            if (xElem1 != null)
                return xElem1.InnerText;
            else
                return "";
        }
        public void SetValue(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            //獲取可執行檔案的路徑和名稱 
            xDoc.Load(System.Windows.Forms.Application.StartupPath + "/" + "Config.xml");
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("Settings");
            xElem1 = (XmlElement)xNode.SelectSingleNode(AppKey);
            if (xElem1 != null)
                xElem1.InnerText = AppValue;
            else
            {
                xElem2 = xDoc.CreateElement(AppKey);
                xElem2.Value = AppValue;
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(Directory.GetCurrentDirectory() + "/" + "Config.xml");
        }


        private void Btn_Save_Click(object sender, EventArgs e)
        {
            SetValue("DatabaseName",this.Txt_Database_Name.Text.Trim());
            MessageBox.Show("配置成功","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            return;
        }


        private void Btn_Dir_Click(object sender, EventArgs e)
        {
            //2012年7月19日修改程式原始碼增加記錄功能使用者選擇路徑之後自動儲存路徑方便下次使用
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "請選擇備份路徑";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                this.Txt_Dir.Text = dialog.SelectedPath;
            }
            else
            {
                return;
            }
        }
        private SQLDMO.Backup backup;
        private void Btn_Backup_Click(object sender, EventArgs e)
        {
            if (this.Txt_Dir.Text.Trim() == "")
            {
                MessageBox.Show("請選擇備份目錄","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            else
            {
                backup = new SQLDMO.Backup();
                SQLDMO.SQLServer sqlServer = new SQLDMO.SQLServer();
                backup.PercentComplete += new BackupSink_PercentCompleteEventHandler(backup_PercentComplete);
                try
                {
                    this.toolStripProgressBar1.Visible = true;
                    this.toolStripProgressBar1.Value = 0;
                    sqlServer.Connect(".", "sa", "sa");
                    backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                    backup.Database = "cpudata";
                    backup.Files = this.Txt_Dir.Text + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".bak";
                    backup.BackupSetName = "cpudata";
                    backup.BackupSetDescription = "資料庫備份";
                    backup.Initialize = true;
                    backup.PercentCompleteNotification = 1;
                    this.Cursor = Cursors.AppStarting;
                    backup.SQLBackup(sqlServer);


                    this.Cursor = Cursors.Default;
                    this.toolStripProgressBar1.Value = 100;
                    MessageBox.Show("資料庫備份完畢", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;


                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //return;
                }
                finally
                {
                    sqlServer.DisConnect();


                }
                backup.PercentComplete += new BackupSink_PercentCompleteEventHandler(backup_PercentComplete);
                backup = null;
            }
        }
        private void backup_PercentComplete(string message,int percent)
        {
            char[] a = new char[] { '0','1','2','3','4','5','6','7','8','9'};
            int startPos = message.IndexOfAny(a);
            int endPos = message.LastIndexOfAny(a);
            int value = Convert.ToInt32(message.Substring(startPos,endPos-startPos+1));
            this.toolStripProgressBar1.Value = value;
            this.toolStripStatusLabel1.Text = "已完成進度"+this.toolStripProgressBar1.Value.ToString() + "%";
            System.Windows.Forms.Application.DoEvents();
 
        }


        private void 設定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config cf = new Config();
            cf.Show();
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            if (dt.Hour==Hour && dt.Minute==Minute && dt.Second==0)
            {
                //開始執行備份
                this.toolStripStatusLabel1.Text = "開始執行資料庫備份程式……";
                backup = new SQLDMO.Backup();
                SQLDMO.SQLServer sqlServer = new SQLDMO.SQLServer();
                backup.PercentComplete += new BackupSink_PercentCompleteEventHandler(backup_PercentComplete);
                try
                {
                    this.toolStripProgressBar1.Visible = true;
                    this.toolStripProgressBar1.Value = 0;
                    sqlServer.Connect(".", "sa", "sa");
                    backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                    backup.Database = "cpudata";
                    backup.Files = this.Txt_Dir.Text + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".bak";
                    backup.BackupSetName = "cpudata";
                    backup.BackupSetDescription = "資料庫備份";
                    backup.Initialize = true;
                    backup.PercentCompleteNotification = 1;
                    this.Cursor = Cursors.AppStarting;
                    backup.SQLBackup(sqlServer);


                    this.Cursor = Cursors.Default;
                    this.toolStripProgressBar1.Value = 100;
                    MessageBox.Show("資料庫備份完畢", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;


                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //return;
                }
                finally
                {
                    sqlServer.DisConnect();


                }
                backup.PercentComplete += new BackupSink_PercentCompleteEventHandler(backup_PercentComplete);
                backup = null;
                this.toolStripStatusLabel1.Text = "勝利油田恆達電氣";
            }
        }


        private void 關閉ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void 還原ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
        }


        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
            } 
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.notifyIcon1.Visible = false;
        }


        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;


        }
    }
}

相關推薦

c#sql Server資料庫自動備份程式

這幾天寫了一個xp下安裝sql Server 2005 express版本的資料庫自動備份程式,大家看看若是有覺得不合理的地方歡迎指正 using System; using System.Collections.Generic; using System.Compone

c#中SQL Server 資料庫的讀語句

資料庫讀寫 CDataBase using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Dat

sql server 2008 自動備份(非維護計劃)

clas .net 最新版 sele sdn base csdn 代理 工具 在一個項目中用到的數據庫是sqlserver 2008 r2 express 。可沒想到express版本的功能有些限制,此前一直都不知道啊。百度百科可以看到它的限制: “1.數據庫的大小限

BCP工具的使用以及C++,SQL server資料庫中呼叫命令列的方法

BCP工具使用: BCP是由SYBASE公司提供的,專門用於資料庫表一級資料備份的工具。 主要引數如下: 基本用法: 遠端地址1的資料庫表student 匯出到本地(遠端ip1(10.189.1.1) ): bcp run.dbo.student out "c:\student

sql server資料庫實時備份_sql資料庫實時備份軟體_資料實時備份

www.syncnavigator.cn SyncNavigator 做資料同步時所支援的資料庫型別: 支援sqlserver 2000-2014所有版本,全相容,和MYsql 4.x 、MYsql 5.x 、MYsql 6.x版本。 來源資料庫和目標資料庫可以版本不同,比如:來源資料庫

C#與SQL Server資料庫連線

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namesp

[原始碼和文件分享]基於C#和SQL SERVER資料庫實現的學生圖書管理系統

1 專案介紹 1.1 課程設計的目標 通過課程集中實踐,要求學生加深對講授內容的理解,累積經驗、學會獨立上機除錯程式;並且逐步達到綜合運用封裝、繼承和多型等C#難點知識,更深地理解面向物件程式設計的基本概念與方法,從而學會利用C#語言解決一般應用問題,能設利用視覺化程式設計技術開發複雜和綜合

[原始碼和文件分享]基於C#和SQL SERVER資料庫實現的餐飲管理系統

摘 要 餐飲管理系統作為一個餐飲的基本管理,是餐飲服務業對職工以及餐飲的日常管理。開發餐飲管理系統,正是完善餐飲業資訊化管理的重要環節。人工操作已很難滿足餐飲業資訊化管理的要求,面對龐大的資訊量,該方式現存在很多弊端。因此,建立現代化的智慧管理系統勢在必行。這樣也大大減輕了餐飲業內部人員的工作量

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

C#連線SQL SERVER資料庫的詳細步驟!

首先,在SQL SEVER裡建立一個名為“Exercise”的資料庫名,在該資料庫下建立一張名為“lianxi”的表。好,現在開始寫程式碼。 在FORM1裡拖一個DATAGIRDVIEW用於顯示錶,在放一個BUTTON用於執行操作。加入名稱空間 using system.d

C#連線SQL Server 資料庫

首先SqlConnection需要引入的名稱空間為System.Data.SqlClient                      string connsql = "se

C++連線SQL Server資料庫

C++連線SQL資料庫第一步 系統配置 1.設定SQLSERVER伺服器為SQL登入方式,並且系統安全性中的sa使用者要設定登入功能為“啟用”,還有必須要有密碼。 2.需要在ODBC中進行資料來源配置,資料來源選\”SQL SERVER”,登入方式使用“使用輸入使用者登入I

用分離、附加的方式實現sql server資料庫備份和還原

一、資料庫分離、附加的說明 SQL Server提供了“分離/附加”資料庫、“備份/還原”資料庫、複製資料庫等多種資料庫的備份和恢復方法。這裡介紹一種學習中常用的“分離/附加”方法,類似於大家熟悉的“檔案拷貝”方法,即把資料庫檔案(.MDF)和對應的日誌檔案(.LDF)再拷貝到任何需要恢復這個資料庫的系統磁

C#連線sql server資料庫的連線字串書寫

1、連線SQLEXPRESS A)、連線到 SQLServer Express Edition 資料庫,下面的連線字串連線到一個名為 Database1 的資料庫: DataSource=.\SQLEXPRESS;Initial Catalog=Database1;Int

c#操作sql server資料庫(ADO.net基礎)

ado.net提供了豐富的資料庫操作,這些操作可以分為三個步驟: 第一,使用SqlConnection物件連線資料庫; 第二,建立SqlCommand物件,負責SQL語句的執行和儲存過程的呼叫;

C# 連線SQL Server資料庫的幾種方式--server+data source等方式

<span style="font-family: Arial; background-color: rgb(255, 255, 255);">如何使用Connection物件連線資料庫?</span> 對於不同的.NET資料提供者,ADO.NET

SQL Server 資料庫備份與恢復

SQL Server 2008 資料庫的備份與恢復 平時敲程式碼習慣了不時的儲存、生成新的解決方案以保證意外發生時能夠及時拯救自己的成果。 對於資料庫這樣的重要資料就更加需要合理備份,下面我們就來一起看看它的備份與恢復吧! SQL資料庫的備份 進入Mic

SQL SERVER 2012資料庫自動備份的方法

SQL SERVER 2012資料庫自動備份的方法 為了防止資料丟失,這裡給大家介紹SQL SERVER2012資料自動備份的方法: 一、開啟SQL SERVER 2012,如圖所示: 伺服器型別:資料庫引擎; 伺服器名稱:127.0.0.1(本地),也可以選擇遠端連線; 身份驗證:包含Wind

SQL Server 資料庫定時自動備份【轉】

[email protected](250) [email protected]='C:\Backup\TestDB1_'+ convert(varchar(50),getdate(),112)+'.bak' BACKUPDATABASE[TestDB1]TO  [email&

SQL Server資料庫備份檔案還原到不同的資料庫xjh測試可以-https://www.yigujin.cn/1269.html

SQL Server 2005 備份檔案還原到新資料庫 2017年07月10日 17:41:49  閱讀 267 次 評論 2 條   上次的『刪除SQLServer2005歷史資料之工作小結』一文中說到由於特殊原因需要刪除某系統的歷史資料,在刪除