Beispiel #1
0
        /// <summary>
        /// database backup
        /// </summary>
        /// <returns>Backup is successful</returns>
        public bool DbBackup()
        {
            CreatePath();
            SQLDMO.Backup    oBackup    = new SQLDMO.BackupClass();
            SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
            try
            {
                oSQLServer.LoginSecure = false;
                oSQLServer.Connect(server, uid, pwd);
                oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
                oBackup.PercentComplete     += pceh;
                oBackup.Database             = database;
                oBackup.Files                = backPath;
                oBackup.BackupSetName        = database;
                oBackup.BackupSetDescription = "Database Backup";
                oBackup.Initialize           = true;
                oBackup.SQLBackup(oSQLServer);
                return(true);
            }
            catch (Exception ex)
            {
                return(false);

                throw ex;
            }
            finally
            {
                oSQLServer.DisConnect();
            }
        }
Beispiel #2
0
 /// <summary>
 ///  备份  
 /// </summary>
 /// <param name="url">备份的地址  必须是绝对路径 </param>
 /// <returns></returns>
 public bool DbBackup(string url)
 {
     SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
     SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
     try
     {
         oSQLServer.LoginSecure = false;
         oSQLServer.Connect(server, uid, pwd);
         oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
         oBackup.Database = database;
         oBackup.Files = url;//"d:\Northwind.bak";
         oBackup.BackupSetName = database;
         oBackup.BackupSetDescription = "数据库备份";
         oBackup.Initialize = true;
         oBackup.SQLBackup(oSQLServer);
         return true;
     }
     catch
     {
         return false;
         throw;
     }
     finally
     {
         oSQLServer.DisConnect();
     }
 }
Beispiel #3
0
        /**/
        /// <summary>
        /// 构造文件名
        /// </summary>
        /// <returns>文件名</returns>
        public string CreatePath()
        {
            return(HttpContext.Current.Server.MapPath(path).ToString());
        }

        /// <summary>
        /// 切割字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="bg"></param>
        /// <param name="ed"></param>
        /// <returns></returns>
        public string StringCut(string str, string bg, string ed)
        {
            string sub;

            sub = str.Substring(str.IndexOf(bg) + bg.Length);
            sub = sub.Substring(0, sub.IndexOf(";"));
            return(sub);
        }

        /**/
        /// <summary>
        /// 数据库备份
        /// </summary>
        /// <returns>备份是否成功</returns>
        public bool DbBackup()
        {
            string path = CreatePath();

            SQLDMO.Backup    oBackup    = new SQLDMO.BackupClass();
            SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
            try
            {
                oSQLServer.LoginSecure = false;
                oSQLServer.Connect(server, uid, pwd);
                oBackup.Action               = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                oBackup.Database             = database;
                oBackup.Files                = path;
                oBackup.BackupSetName        = database;
                oBackup.BackupSetDescription = "数据库备份";
                oBackup.Initialize           = true;
                oBackup.SQLBackup(oSQLServer);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);

                throw ex;
            }
            finally
            {
                oSQLServer.DisConnect();
            }
        }
Beispiel #4
0
        protected void Save_Click(object sender, EventArgs e)
        {
            //try
            //{
            SQLDMO.Backup    backup    = new SQLDMO.BackupClass();
            SQLDMO.SQLServer sqlserver = new SQLDMO.SQLServerClass();
            sqlserver.LoginSecure = false;
            sqlserver.Connect("" + sUrl + "", "" + sUser + "", "" + sPwd + "");        //连接
            backup.Action   = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
            backup.Database = "" + sName + "";                                         //数据库
            string str1 = this.dburl.Text;

            backup.Files                = str1;                                           //路径
            backup.BackupSetName        = "" + sDbUrl + "";                               //数据库名
            backup.BackupSetDescription = "数据库备份";
            backup.Initialize           = true;
            backup.SQLBackup(sqlserver);

            SqlHelper.ExecuteSql("INSERT INTO hk_DbBackUp(DbName,DbUrl,UserID,UserName,SetTimes) VALUES('" + sDbUrl + "','" + hkdb.GetStr(dburl.Text) + "','" + this.Session["userid"] + "','" + this.Session["username"] + "',GETDATE())");

            //日志
            mydb.InsertLog("备份数据库【" + sDbUrl + "】", "60109");

            mydb.Alert_Refresh_Close("备份成功!", "Sjkbf.aspx");
            //}
            //catch
            //{
            //    mydb.Alert("备份失败,请检查备份路径及相关参数后重试!");
            //}
        }
Beispiel #5
0
 //数据库备份
 public static void DbBackup(string savefilepath)
 {
     SQLDMO.Backup    oBackup    = new SQLDMO.BackupClass();
     SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
     try
     {
         oSQLServer.LoginSecure = true;
         oSQLServer.Connect(".", "sa", "sa");//服务器名、账号、密码
         oBackup.Action               = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
         oBackup.Database             = "EatingTradDB";
         oBackup.Files                = savefilepath;
         oBackup.BackupSetName        = "EatingTradDB";
         oBackup.BackupSetDescription = "数据库备份";
         oBackup.Initialize           = true;
         oBackup.SQLBackup(oSQLServer);
     }
     catch
     {
         throw;
     }
     finally
     {
         oSQLServer.DisConnect();
     }
 }
Beispiel #6
0
 /// <summary>
 /// SQL数据库备份
 /// </summary>
 /// <param name="ServerIP">SQL服务器IP或(Localhost)</param>
 /// <param name="LoginName">数据库登录名</param>
 /// <param name="LoginPass">数据库登录密码</param>
 /// <param name="DBName">数据库名</param>
 /// <param name="BackPath">备份到的路径</param>
 public static bool SQLBACK(string ServerIP, string LoginName, string LoginPass, string DBName, string BackPath)
 {
     SQLDMO.Backup    oBackup    = new SQLDMO.BackupClass();
     SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
     try
     {
         oSQLServer.LoginSecure = false;
         oSQLServer.Connect(ServerIP, LoginName, LoginPass);
         oBackup.Database             = DBName;
         oBackup.Files                = BackPath;
         oBackup.BackupSetName        = DBName;
         oBackup.BackupSetDescription = "数据库备份";
         oBackup.Initialize           = true;
         oBackup.SQLBackup(oSQLServer);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
     finally
     {
         oSQLServer.DisConnect();
     }
 }
Beispiel #7
0
        /// <summary>
        ///  备份  
        /// </summary>
        /// <param name="url">备份的地址  必须是绝对路径 </param>
        /// <returns></returns>
        public bool DbBackup(string url)
        {
            SQLDMO.Backup    oBackup    = new SQLDMO.BackupClass();
            SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
            try
            {
                oSQLServer.LoginSecure = false;
                oSQLServer.Connect(server, uid, pwd);
                oBackup.Action               = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                oBackup.Database             = database;
                oBackup.Files                = url;//"d:\Northwind.bak";
                oBackup.BackupSetName        = database;
                oBackup.BackupSetDescription = "数据库备份";
                oBackup.Initialize           = true;
                oBackup.SQLBackup(oSQLServer);
                return(true);
            }
            catch
            {
                return(false);

                throw;
            }
            finally
            {
                oSQLServer.DisConnect();
            }
        }
Beispiel #8
0
 /// <summary>
 /// 数据库的备份和实时进度显示
 /// </summary>
 /// <param name="strDbName"></param>
 /// <param name="strFileName"></param>
 /// <param name="pgbMain"></param>
 /// <returns></returns>
 public bool BackUPDB(string strDbName, string strFileName)
 {
     SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
     try
     {
         svr.Connect(ServerName, UserName, Password);
         SQLDMO.Backup bak = new SQLDMO.BackupClass();
         bak.Action     = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
         bak.Initialize = true;
         bak.Files      = strFileName;
         bak.Database   = strDbName;
         bak.SQLBackup(svr);
         return(true);
     }
     catch (Exception err)
     {
         //throw (new Exception("备份数据库失败" + err.Message));
         ShowError("连接数据库出错:" + err.Message);
         return(false);
     }
     finally
     {
         svr.DisConnect();
     }
 }
Beispiel #9
0
        /// <summary>
        /// SQL数据库备份
        /// </summary>
        /// <param name="filename">要备份到的文件全路径</param>
        /// <param name="connStrBuilder">连接字符串构造器</param>
        /// <param name="Backup_PercentComplete">进度</param>
        /// <param name="oBackup">数据库备份服务对象</param>
        /// <param name="remark">备份备注</param>
        public bool SQLDbBackup(string filename, SqlConnectionStringBuilder connStrBuilder, SQLDMO.BackupSink_PercentCompleteEventHandler Backup_PercentComplete, out SQLDMO.Backup oBackup, string remark)
        {
            string   ServerIP      = connStrBuilder.DataSource;
            string   LoginUserName = connStrBuilder.UserID;
            string   LoginPass     = connStrBuilder.Password;
            string   DBName        = connStrBuilder.InitialCatalog;
            FileInfo fi            = new FileInfo(filename);
            string   DBFile        = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);

            oBackup = new SQLDMO.BackupClass();
            SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
            try
            {
                oSQLServer.LoginSecure = false;
                oSQLServer.Connect(ServerIP, LoginUserName, LoginPass);
                oBackup.Action               = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                oBackup.PercentComplete     += Backup_PercentComplete;
                oBackup.Database             = DBName;
                oBackup.Files                = @"" + string.Format("[{0}]", filename) + "";
                oBackup.BackupSetName        = DBFile;
                oBackup.BackupSetDescription = "备份集" + DBFile;
                oBackup.Initialize           = true;
                oBackup.SQLBackup(oSQLServer);
                return(true);
            }
            catch (Exception e)
            {
                MessageBox.Show("数据库备份失败:" + e.Message);
                return(false);
            }
            finally
            {
                oSQLServer.DisConnect();
            }
        }
Beispiel #10
0
        public static bool backupDB(string strdbname, string strfilename)
        {
            string conStr = ConfigurationManager.AppSettings["SqlConString"].ToString();

            string[] con       = conStr.Split(';');
            int      nameIndex = con[2].IndexOf('=') + 1;
            string   username  = con[2].Substring(nameIndex, con[2].Length - nameIndex);
            int      pwdIndex  = con[3].IndexOf('=') + 1;
            string   pwd       = con[3].Substring(pwdIndex, con[3].Length - pwdIndex);
            int      ipIndex   = con[0].IndexOf('=') + 1;
            string   ip        = con[0].Substring(ipIndex, con[0].Length - ipIndex);

            string server   = ip;
            string uid      = username;
            string password = pwd;

            // 引用 DLL 文件,需要设置项目目标框架为 .NET framewo 2.0
            SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
            try
            {
                svr.Connect(server, uid, password);
                SQLDMO.Backup bak = new SQLDMO.BackupClass();
                bak.Action     = 0;
                bak.Initialize = true;

                //SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(step);
                //bak.PercentComplete += pceh;
                bak.Files    = strfilename;
                bak.Database = "CarSecretary";
                bak.SQLBackup(svr);
                return(true);
            }
            catch (Exception ex)
            {
                //CarLog.WriteLog(ex.Message);
                //MessageBox.Show("备份数据库失败,请确保没有其他用户使用数据库!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }
            finally
            {
                svr.DisConnect();
            }
        }
Beispiel #11
0
        public static bool backupDB(string strdbname, string strfilename)
        {
            string conStr = ConfigurationManager.AppSettings["SqlConString"].ToString();
            string[] con = conStr.Split(';');
            int nameIndex = con[2].IndexOf('=') + 1;
            string username = con[2].Substring(nameIndex, con[2].Length - nameIndex);
            int pwdIndex = con[3].IndexOf('=') + 1;
            string pwd = con[3].Substring(pwdIndex, con[3].Length - pwdIndex);
            int ipIndex = con[0].IndexOf('=') + 1;
            string ip = con[0].Substring(ipIndex, con[0].Length - ipIndex);

            string server = ip;
            string uid = username;
            string password = pwd;

            SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
            try
            {
                svr.Connect(server, uid, password);
                SQLDMO.Backup bak = new SQLDMO.BackupClass();
                bak.Action = 0;
                bak.Initialize = true;

                //SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(step);
                //bak.PercentComplete += pceh;
                bak.Files = strfilename;
                bak.Database = "CarSecretary";
                bak.SQLBackup(svr);
                return true;
            }
            catch (Exception ex)
            {
                //CarLog.WriteLog(ex.Message);
                //MessageBox.Show("备份数据库失败,请确保没有其他用户使用数据库!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            finally
            {
                svr.DisConnect();
            }
        }
Beispiel #12
0
 private void btnBackUp_Click(object sender, EventArgs e)
 {
     if (textBoxLJBK.Text == "")
     {
         MessageBox.Show("请确定数据库备份地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         return;
     }
     SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
     SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
     try
     {
         oSQLServer.LoginSecure = false;
         //下面设置登录sql服务器的ip,登录名,登录密码
         oSQLServer.Connect(strDataBaseAddr, strDataBaseUser, strDataBasePass);
         oBackup.Action = 0;
         //下面两句是显示进度条的状态
         SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step2);
         oBackup.PercentComplete += pceh;
         //数据库名称:
         oBackup.Database = strDataBaseName;
         //备份的路径
         oBackup.Files = textBoxLJBK.Text;
         //备份的文件名
         oBackup.BackupSetName = "BUSINESS";
         oBackup.BackupSetDescription = "数据库备份";
         oBackup.Initialize = true;
         oBackup.SQLBackup(oSQLServer);
         MessageBox.Show("备份成功!", "提示");
     }
     catch
     {
         MessageBox.Show("备份失败!", "提示");
     }
     finally
     {
         oSQLServer.DisConnect();
         toolStripProgressBar1.Value = 0;
     }
 }
Beispiel #13
0
        /// <summary>
        /// 数据库备份
        /// </summary>
        public static bool DbBackup(string url)
        {
            SQLDMO.Backup    oBackup    = new SQLDMO.BackupClass();
            SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
            try
            {
                oSQLServer.LoginSecure = false;

                oSQLServer.Connect(System.Configuration.ConfigurationManager.AppSettings["Server"], System.Configuration.ConfigurationManager.AppSettings["User"], System.Configuration.ConfigurationManager.AppSettings["Password"]);

                oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;

                oBackup.Database = System.Configuration.ConfigurationManager.AppSettings["DB"];

                oBackup.Files = url;//"d:\Northwind.bak";

                oBackup.BackupSetName = System.Configuration.ConfigurationManager.AppSettings["DB"];

                oBackup.BackupSetDescription = "数据库备份";

                oBackup.Initialize = true;

                oBackup.SQLBackup(oSQLServer);

                return(true);
            }
            catch
            {
                return(false);

                throw;
            }
            finally
            {
                oSQLServer.DisConnect();
            }
        }
Beispiel #14
0
        /// <summary>
        /// SQL数据库备份
        /// </summary>
        /// <param name="path">备份到的路径< /param>
        /// <param name="Backup_PercentComplete">进度</param>
        /// <param name="oBackup">数据库备份服务对象</param>
        /// <param name="remark">备份备注</param>
        public static bool SQLDbBackup(string path, SQLDMO.BackupSink_PercentCompleteEventHandler Backup_PercentComplete, out SQLDMO.Backup oBackup, string remark = null)
        {
            SqlConnectionStringBuilder connStrBuilder = new SqlConnectionStringBuilder(TopFashion.Configs.ConnString);
            string ServerIP      = connStrBuilder.DataSource;
            string LoginUserName = connStrBuilder.UserID;
            string LoginPass     = connStrBuilder.Password;
            string DBName        = connStrBuilder.InitialCatalog;
            string dir           = path + "\\" + DBName;

            dir = dir.Replace("\\\\", "\\");

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            string locale     = string.Empty;
            string username   = string.Empty;
            string password   = string.Empty;
            string authority  = string.Empty;
            string RemoteAuth = TopFashion.Configs.RemoteAuth;

            if (!string.IsNullOrEmpty(RemoteAuth))
            {
                string[] ra = RemoteAuth.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (ra.Length == 4)
                {
                    locale    = ra[0];
                    username  = ra[1];
                    password  = ra[2];
                    authority = ra[3];
                }
            }
            System.Management.ManagementScope scope = new System.Management.ManagementScope("\\\\" + ServerIP + "\\root\\cimv2", new System.Management.ConnectionOptions(locale, username, password, authority, System.Management.ImpersonationLevel.Impersonate, System.Management.AuthenticationLevel.Default, true, null, TimeSpan.MaxValue));
            if (ServerIP == "." || ServerIP == "(local)" || ServerIP == "127.0.0.1")
            {
            }
            else
            {
                int i = WmiShareRemote.CreateRemoteDirectory(scope, Path.GetDirectoryName(dir), Directory.GetParent(dir).FullName);
            }
            string DBFile   = DBName + DateTime.Now.ToString("yyyyMMddHHmm");
            string filename = dir + "\\" + DBFile + ".bak";

            if (!File.Exists(filename))
            {
                try
                {
                    FileStream fs = File.Create(filename);
                    fs.Close();
                }
                catch (Exception e)
                {
                    TopFashion.WriteLog.CreateLog("数据库操作", "SQLDbBackup", "error", "无法创建 [" + filename + "] 数据库备份文件!" + Environment.NewLine + e.Message);
                }
            }
            if (ServerIP == "." || ServerIP == "(local)" || ServerIP == "127.0.0.1")
            {
            }
            else
            {
                bool flag = WmiShareRemote.WmiFileCopyToRemote(ServerIP, username, password, dir, "DatabaseBackup", "数据库备份集", null, new string[] { filename }, 0);
            }
            oBackup = new SQLDMO.BackupClass();
            SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
            try
            {
                oSQLServer.LoginSecure = false;
                oSQLServer.Connect(ServerIP, LoginUserName, LoginPass);
                oBackup.Action               = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                oBackup.PercentComplete     += Backup_PercentComplete;
                oBackup.Database             = DBName;
                oBackup.Files                = @"" + string.Format("[{0}]", filename) + "";
                oBackup.BackupSetName        = DBName;
                oBackup.BackupSetDescription = "备份集" + DBName;
                oBackup.Initialize           = true;
                oBackup.SQLBackup(oSQLServer);//这里可能存在问题:比如备份远程数据库的时候,选的路径path却是本地的,恰好是远程服务器上不存在的目录
                TopFashion.SQLDBHelper SqlHelper = new TopFashion.SQLDBHelper();
                SqlHelper.ExecuteSql("insert into Record (DB, Path, Remark) values ('" + DBName + "', '" + filename + "', '" + remark + "')", true);
                return(true);
            }
            catch (Exception e)
            {
                TopFashion.WriteLog.CreateLog("数据库操作", "SQLDbBackup", "error", "备份时出错:" + e.Message);
            }
            finally
            {
                oSQLServer.DisConnect();
            }
            return(false);
        }
Beispiel #15
0
 /// <summary>
 /// ���ݿ�ı��ݺ�ʵʱ������ʾ 
 /// </summary>
 /// <param name="strDbName"></param>
 /// <param name="strFileName"></param>
 /// <param name="pgbMain"></param>
 /// <returns></returns>
 public bool BackUPDB(string strDbName, string strFileName)
 {
     SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
     try
     {
         svr.Connect(ServerName, UserName, Password);
         SQLDMO.Backup bak = new SQLDMO.BackupClass();
         bak.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
         bak.Initialize = true;
         bak.Files = strFileName;
         bak.Database = strDbName;
         bak.SQLBackup(svr);
         return true;
     }
     catch (Exception err)
     {
         //throw (new Exception("�������ݿ�ʧ��" + err.Message));
         ShowError("�������ݿ�����" + err.Message);
         return false;
     }
     finally
     {
         svr.DisConnect();
     }
 }
Beispiel #16
0
        /// <summary>
        /// 备份指定数据库文件
        /// </summary>
        /// <param name="strDbName">数据库名称</param>
        /// <param name="strFileName">备份数据库的路径</param>
        /// <param name="strServerName">服务器名称</param>
        /// <param name="strUserName">用户名</param>
        /// <param name="strPassword">密码</param>
        /// <param name="prosBar">进度条</param>
        /// <returns></returns>
        public static bool BackUPDB(string strDbName, string strFileName, string strServerName, string strUserName, string strPassword, ProgressBar bar)
        {
            #region [ 判断磁盘剩余空间是否可进行备份 ]

            DBAcess dba   = new DBAcess();
            DataSet tmpds = dba.GetDataSet("exec sp_spaceused");
            if (tmpds.Tables.Count > 0 && tmpds.Tables[0] != null)
            {
                // 得到数据库大小
                string tmpStr = tmpds.Tables[0].Rows[0]["database_size"].ToString();
                int    dbSize = Convert.ToInt32(tmpStr.Substring(0, tmpStr.LastIndexOf(".")));
                // 获取磁盘剩余空间大小
                try
                {
                    DriveInfo d        = new DriveInfo(strFileName.Substring(0, 1));
                    int       diskSize = Convert.ToInt32(d.AvailableFreeSpace / 1024 / 1024);
                    if (diskSize < dbSize)
                    {
                        MessageBox.Show("备份数据库所需空间不能小于" + dbSize + "M\r\n磁盘[" + d.Name + "]存储空间过小,无法备份");
                        return(false);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("路径不正确");
                    return(false);
                    //throw;
                }
            }

            #endregion

            pBar = bar;
            string           strTmp  = "";
            string           tmpPath = strFileName.Substring(0, strFileName.LastIndexOf("\\")).ToString();
            int              isEmpty = tmpPath.IndexOf(" ");
            SQLDMO.SQLServer svr     = null;
            try
            {
                svr = new SQLDMO.SQLServerClass();
                // 连接到数据库
                svr.Connect(strServerName, strUserName, strPassword);
                SQLDMO.Backup bak = new SQLDMO.BackupClass();
                bak.Action     = 0;
                bak.Initialize = true;

                #region 进度条处理

                if (pBar != null)
                {
                    pBar.Visible = true;
                    SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
                    bak.PercentComplete += pceh;
                }

                #endregion

                #region [ 文件夹名称中有空格: 备份前的处理 ]

                // 文件夹不存在时自动创建
                if (!Directory.Exists(tmpPath))
                {
                    Directory.CreateDirectory(tmpPath);
                }

                // 文件夹名称 中有空格 备份文件路径设置为根目录的临时文件夹tmpBackup中
                if (isEmpty > 1 && strFileName.Substring(4).LastIndexOf("\\") > 1)
                {
                    strTmp = strFileName.Substring(0, 1).ToString() + ":\\tmp_backup.kj";
                }
                else
                {
                    strTmp = strFileName;
                }

                #endregion

                // 数据库的备份的名称及文件存放位置
                bak.Files    = strTmp;
                bak.Database = strDbName;

                // 备份
                bak.SQLBackup(svr);
            }
            catch (Exception err)
            {
                if (SqlErrRepair(err.Message.ToString()))
                {
                    BackUPDB(strDbName, strFileName, strServerName, strUserName, strPassword, pBar);
                    return(true);
                }
                return(false);
                //MessageBox.Show("备份数据库失败");
            }
            finally
            {
                if (svr != null)
                {
                    svr.DisConnect();
                }

                #region [ 文件夹名称中有空格: 备份完成后的处理 ]

                // 文件夹名称 中有空格 将备份的文件移动到用户指定的文件夹并将临时目录删除
                if (isEmpty > 1 && strFileName.Substring(4).LastIndexOf("\\") > 1)
                {
                    // 文件存在则替换
                    if (File.Exists(strFileName.Substring(strFileName.LastIndexOf("\\") + 2)))
                    {
                        File.Delete(strFileName.Substring(strFileName.LastIndexOf("\\") + 2));
                    }
                    File.Move(strTmp, strFileName);
                }

                #endregion
            }
            return(true);
        }
Beispiel #17
0
 /// <summary> 
 /// SQL数据库备份 
 /// </summary> 
 /// <param name="ServerIP">SQL服务器IP或(Localhost)</param> 
 /// <param name="LoginName">数据库登录名</param> 
 /// <param name="LoginPass">数据库登录密码</param> 
 /// <param name="DBName">数据库名</param> 
 /// <param name="BackPath">备份到的路径</param> 
 public static void SQLBACK(string ServerIP, string LoginName, string LoginPass, string DBName, string BackPath)
 {
     SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
     SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
     try
     {
         oSQLServer.LoginSecure = false;
         oSQLServer.Connect(ServerIP, LoginName, LoginPass);
         oBackup.Database = DBName;
         oBackup.Files = BackPath;
         oBackup.BackupSetName = DBName;
         oBackup.BackupSetDescription = "数据库备份";
         oBackup.Initialize = true;
         oBackup.SQLBackup(oSQLServer);
     }
     catch (Exception e)
     {
         throw new Exception(e.ToString());
     }
     finally
     {
         oSQLServer.DisConnect();
     }
 }
Beispiel #18
0
        /// <summary>
        /// 备份指定数据库文件
        /// </summary>
        /// <param name="strDbName">数据库名称</param>
        /// <param name="strFileName">备份数据库的路径</param>
        /// <param name="strServerName">服务器名称</param>
        /// <param name="strUserName">用户名</param>
        /// <param name="strPassword">密码</param>
        /// <param name="prosBar">进度条</param>
        /// <returns></returns>
        public static bool BackUPDB(string strDbName, string strFileName, string strServerName, string strUserName, string strPassword, ProgressBar bar)
        {
            #region [ 判断磁盘剩余空间是否可进行备份 ]

            DBAcess dba = new DBAcess();
            DataSet tmpds = dba.GetDataSet("exec sp_spaceused");
            if (tmpds.Tables.Count > 0 && tmpds.Tables[0] != null)
            {
                // 得到数据库大小
                string tmpStr = tmpds.Tables[0].Rows[0]["database_size"].ToString();
                int dbSize = Convert.ToInt32(tmpStr.Substring(0, tmpStr.LastIndexOf(".")));
                // 获取磁盘剩余空间大小
                try
                {
                    DriveInfo d = new DriveInfo(strFileName.Substring(0, 1));
                    int diskSize = Convert.ToInt32(d.AvailableFreeSpace / 1024 / 1024);
                    if (diskSize < dbSize)
                    {
                        MessageBox.Show("备份数据库所需空间不能小于" + dbSize + "M\r\n磁盘[" + d.Name + "]存储空间过小,无法备份");
                        return false;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("路径不正确");
                    return false;
                    //throw;
                }
            }

            #endregion

            pBar = bar;
            string strTmp = "";
            string tmpPath = strFileName.Substring(0, strFileName.LastIndexOf("\\")).ToString();
            int isEmpty = tmpPath.IndexOf(" ");
            SQLDMO.SQLServer svr = null;
            try
            {
                svr = new SQLDMO.SQLServerClass();
                // 连接到数据库
                svr.Connect(strServerName, strUserName, strPassword);
                SQLDMO.Backup bak = new SQLDMO.BackupClass();
                bak.Action = 0;
                bak.Initialize = true;

                #region 进度条处理

                if (pBar != null)
                {
                    pBar.Visible = true;
                    SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
                    bak.PercentComplete += pceh;
                }

                #endregion

                #region [ 文件夹名称中有空格: 备份前的处理 ]

                // 文件夹不存在时自动创建
                if (!Directory.Exists(tmpPath))
                {
                    Directory.CreateDirectory(tmpPath);
                }

                // 文件夹名称 中有空格 备份文件路径设置为根目录的临时文件夹tmpBackup中
                if (isEmpty > 1 && strFileName.Substring(4).LastIndexOf("\\") > 1)
                {
                    strTmp = strFileName.Substring(0, 1).ToString() + ":\\tmp_backup.kj";
                }
                else
                {
                    strTmp = strFileName;
                }

                #endregion

                // 数据库的备份的名称及文件存放位置
                bak.Files = strTmp;
                bak.Database = strDbName;

                // 备份
                bak.SQLBackup(svr);
            }
            catch (Exception err)
            {
                if (SqlErrRepair(err.Message.ToString()))
                {
                    BackUPDB(strDbName, strFileName, strServerName, strUserName, strPassword, pBar);
                    return true;
                }
                return false;
                //MessageBox.Show("备份数据库失败");

            }
            finally
            {
                if (svr != null)
                {
                    svr.DisConnect();
                }

                #region [ 文件夹名称中有空格: 备份完成后的处理 ]

                // 文件夹名称 中有空格 将备份的文件移动到用户指定的文件夹并将临时目录删除
                if (isEmpty > 1 && strFileName.Substring(4).LastIndexOf("\\") > 1)
                {
                    // 文件存在则替换
                    if (File.Exists(strFileName.Substring(strFileName.LastIndexOf("\\") + 2)))
                    {
                        File.Delete(strFileName.Substring(strFileName.LastIndexOf("\\") + 2));
                    }
                    File.Move(strTmp, strFileName);
                }

                #endregion
            }
            return true;
        }