说明:为了定时备份服务器上的数据库并压缩到指定目录,方便下载到本地而写本程序。配合windows的任务计划,可以达到定时备份数据库的目的。

程序需引用SQLDMO.DLL,如电脑上已安装sqlserver,可在C:\Program Files\Microsoft SQL Server\80\Tools\Binn\找到

 

string ServerName = System.Configuration.ConfigurationSettings.AppSettings["ServerName"];//数据库服务器名
        string UserName = System.Configuration.ConfigurationSettings.AppSettings["UserName"];//数据库用户名
        string Password = System.Configuration.ConfigurationSettings.AppSettings["Password"];//密码
        string strDbName = System.Configuration.ConfigurationSettings.AppSettings["strDbName"];//数据库名
        string FilePathBak = System.Configuration.ConfigurationSettings.AppSettings["FilePathBak"];//备份后的文件保存路径(.bak),不包括文件名
        string FilePathRar = System.Configuration.ConfigurationSettings.AppSettings["FilePathRar"];//压缩文件保存的路径,这里不包括压缩后的文件名

        public Form1()
        {
            InitializeComponent();

            bool backup = BackUPDB(ServerName, UserName, Password, strDbName, FilePathBak);
            if (backup)
            {
                rar(FilePathBak, FilePathRar);
                del();
            }
            System.Environment.Exit(0);// 这是最彻底的退出方式,不管什么线程都被强制退出,把程序结束的很干净。           
        }


        /// <summary>
        /// 备份数据库
        /// </summary>
        /// <param name="ServerName">服务器名</param>
        /// <param name="UserName">登录账号</param>
        /// <param name="Password">密码</param>
        /// <param name="strDbName">待备份的数据库名</param>
        /// <param name="FilePathBak">备份后的文件保存路径</param>
        /// <returns></returns>
        public bool BackUPDB(string ServerName, string UserName, string Password, string strDbName, string FilePathBak)
        {
            SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
            SQLDMO.Backup bak = new SQLDMO.BackupClass();
            try
            {
                svr.LoginSecure = false;
                svr.Connect(ServerName, UserName, Password);
                bak.Action = 0; //SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                bak.Initialize = true;

                bak.Files = FilePathBak + strDbName + System.DateTime.Now.ToString("yyyyMMdd") + ".bak";//备份后的文件保存路径+文件名(F:\\databack\\fireweb20100810.bak)
                bak.Database = strDbName;
                bak.BackupSetName = strDbName;
                bak.BackupSetDescription = "数据库备份";
                bak.SQLBackup(svr);

                return true;
            }
            catch (Exception err)
            {
                throw (new Exception("备份数据库失败" + err.Message));
            }
            finally
            {
                svr.DisConnect();
            }
        }

        /// <summary>
        /// 压缩指定文件到指定文件夹
        /// </summary>
        /// <param name="path">被压缩的文件的路径,文件本身在方法中写明,因为文件名要由当前时间判断</param>
        /// <param name="rarPath">压缩后的保存路径</param>
        /// <returns></returns>
        public bool rar(string path, string rarPath)
        {
            bool flag = false;
            System.Diagnostics.Process Pc1 = new System.Diagnostics.Process();
            Pc1.StartInfo.FileName = "Winrar.exe";
            Pc1.StartInfo.CreateNoWindow = false;
            string fileName = strDbName + System.DateTime.Now.ToString("yyyyMMdd")+".bak";
            string rarFileName = strDbName + System.DateTime.Now.ToString("yyyyMMdd") + ".rar";
            path += fileName;//解压前的文件路径+文件名
            rarPath += rarFileName;//解压后的路径+文件名
            Pc1.StartInfo.Arguments = " a -ep " + rarPath + " " + path;//-ep 表示:从名称中排除路径,即压缩时不带各层目录
            Pc1.Start();
            if (Pc1.HasExited)
            {
                int iExitCode = Pc1.ExitCode;
                if (iExitCode == 0)
                {
                    flag = true;
                }
                else
                {
                    flag = false;
                }
                Pc1.Kill();
                Pc1.Close();
                Pc1.Dispose();
            }
            return flag;
        }

        /// <summary>
        /// 由于每天备份一次,所以要把多余的备份文件和压缩文件删除,只保留最新的5个
        /// </summary>
        public void del()
        {
            //删除bak文件
            int count1 = 0;
            ArrayList al1 = new ArrayList();
            DirectoryInfo diPathBak = new DirectoryInfo(FilePathBak);
            foreach (FileInfo fi in diPathBak.GetFiles())
            {
                if (fi.Name.Length > 12)//每个备份的bak的文件名长度一定会大于12(20100808.bak)
                {
                    if (fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length - 8).Equals(strDbName) && fi.Extension.Equals(".bak"))
                    {
                        count1++;
                        al1.Add(fi.Name);
                        if (count1 > 5)
                        {
                            string filename = al1[0].ToString();//删除第一个(由于GetFiles()方法按名称升序排序取文件,即删除最早的)
                            File.Delete(diPathBak + filename);
                            al1.RemoveAt(0);
                            count1--;
                        }
                    }
                }
            }


            //删除rar文件
            int count = 0;
            ArrayList al = new ArrayList();
            DirectoryInfo diPathRar = new DirectoryInfo(FilePathRar);
            foreach (FileInfo fi in diPathRar.GetFiles())
            {
                if (fi.Name.Length > 12)//每个备份的bak的文件名长度一定会大于12(20100808.bak)
                {
                    if (fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length - 8).Equals(strDbName) && fi.Extension.Equals(".rar"))
                    {
                        count++;
                        al.Add(fi.Name);
                        if (count > 5)
                        {
                            string filename = al[0].ToString();//删除第一个(由于GetFiles()方法按名称升序排序取文件,即删除最早的)
                            File.Delete(diPathRar + filename);
                            al.RemoveAt(0);
                            count--;
                        }

                    }
                }
            }
        }

posted on 2010-08-10 21:00  不远道人  阅读(1391)  评论(0编辑  收藏  举报