狠狠色丁香婷婷综合尤物/久久精品综合一区二区三区/中国有色金属学报/国产日韩欧美在线观看 - 国产一区二区三区四区五区tv

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

C#實現SQL SERVER數據庫備份的兩種方法比較

admin
2018年1月30日 23:58 本文熱度 6978
先把代碼貼上吧
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
namespace DBAdmin
{
    public class DbBackUpAndRestore
    {
        /// <summary>
        /// 服務器
        /// </summary>
        private string server = "";
        public string Server
        {
            get { return this.server; }
            set { this.server = value; }
        }
        /// <summary>
        /// 登錄名
        /// </summary>
        private string uid = "";
        public string UID
        {
            get { return this.uid; }
            set { this.uid = value; }
        }
        /// <summary>
        /// 登錄密碼
        /// </summary>
        private string pwd = "";
        public string PWD
        {
            get { return this.pwd; }
            set { this.pwd = value; }
        }
        /// <summary>
        /// 要操作的數據庫
        /// </summary>
        private string database = "";
        public string Database
        {
            get { return this.database; }
            set { this.database = value; }
        }
        /// <summary>
        /// 數據庫連接字符串
        /// </summary>
        private string conn = "";
        /// <summary>
        /// 備份路經
        /// </summary>
        private string backPath = "";
        public string BackPath
        {
            get { return this.backPath; }
            set { this.backPath = value; }
        }
        /// <summary>
        /// 還原文件路經
        /// </summary>
        private string restoreFile = "";
        public string RestoreFile
        {
            get { return this.restoreFile; }
            set { this.restoreFile = value; }
        }
        private ProgressBar bar;
        public ProgressBar Bar
        {
            get { return bar; }
            set { bar = value; }
        }
        /// <summary>
        /// DbBackUpAndRestore類的構造函數
        /// </summary>
        public DbBackUpAndRestore()
        {
        }
        /// <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>
        private void CreatePath()
        {
            string CurrTime = System.DateTime.Now.ToString();
            CurrTime = CurrTime.Replace("-", "");
            CurrTime = CurrTime.Replace(":", "");
            CurrTime = CurrTime.Replace(" ", "");
            CurrTime = CurrTime.Substring(0, 12);
            backPath += "http://_db_" + CurrTime + ".BAK";
        }
        private void Step(string message, int percent)
        {
            Bar.Value = percent;
        }
        /// <summary>
        /// 數據庫備份
        /// </summary>
        /// <returns>備份是否成功</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 = "數據庫備份";
                oBackup.Initialize = true;
                oBackup.SQLBackup(oSQLServer);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }
            finally
            {
                oSQLServer.DisConnect();
            }
        }
        /// <summary>
        /// 數據庫恢復
        /// </summary>
        public string DbRestore()
        {
            if (exepro() != true)
            {
                return "操作失敗";
            }
            else
            {
                SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
                SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
                try
                {
                    exepro();
                    oSQLServer.LoginSecure = false;
                    oSQLServer.Connect(server, uid, pwd);
                    oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
                    SQLDMO.RestoreSink_PercentCompleteEventHandler pceh = new SQLDMO.RestoreSink_PercentCompleteEventHandler(Step);
                    oRestore.PercentComplete += pceh;
                    oRestore.Database = database;
                    ///自行修改
                    oRestore.Files = restoreFile;
                    oRestore.FileNumber = 1;
                    oRestore.ReplaceDatabase = true;
                    oRestore.SQLRestore(oSQLServer);
                    return "數據庫恢復成功";
                }
                catch (Exception e)
                {
                    return "恢復數據庫失敗,原因:" + e.Message;
                    throw e;
                }
                finally
                {
                    oSQLServer.DisConnect();
                }
            }
        }
        /// <summary>
        /// 殺死當前庫的所有進程
        /// </summary>
        /// <returns></returns>
        private bool exepro()
        {
            bool success = true;
            SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
            try
            {
                svr.Connect(server, uid, pwd);
                //取得所有的進程列表
                SQLDMO.QueryResults qr = svr.EnumProcesses(-1);
                int iColPIDNum = -1;
                int iColDbName = -1;
                //找到和要恢復數據庫相關的進程
                for (int i = 1; i <= qr.Columns; i++)
                {
                    string strName = qr.get_ColumnName(i);
                    if (strName.ToUpper().Trim() == "SPID")
                    {
                        iColPIDNum = i;
                    }
                    else if (strName.ToUpper().Trim() == "DBNAME")
                    {
                        iColDbName = i;
                    }
                    if (iColPIDNum != -1 && iColDbName != -1)
                        break;
                }
                //將相關進程關閉  
                for (int i = 1; i <= qr.Rows; i++)
                {
                    int lPID = qr.GetColumnLong(i, iColPIDNum);
                    string strDBName = qr.GetColumnString(i, iColDbName);
                    if (strDBName.ToUpper() == database)
                        svr.KillProcess(lPID);
                }
            }
            catch (Exception ex)
            {
                success = false;
            }
            return success;
        }
        public bool Operate(bool isBackup)
        {
            //備份:use master;backup database @name to disk=@path;
            //恢復:use master;restore database @name from disk=@path;
            SqlConnection connection = new SqlConnection("Data Source=" + server + ";initial catalog=" + database + ";user id=" + uid + ";password=" + pwd + ";");
            if (!restoreFile.EndsWith(".bak"))
            {
                restoreFile += ".bak";
            }
            if (isBackup)//備份數據庫
            {
                SqlCommand command = new SqlCommand("use master;backup database @name to disk=@path;", connection);
                connection.Open();
                command.Parameters.AddWithValue("@name", Database);
                command.Parameters.AddWithValue("@path", restoreFile);
                command.ExecuteNonQuery();
                connection.Close();
            }
            else//恢復數據庫
            {
                SqlCommand command = new SqlCommand("use master;restore database @name from disk=@path;", connection);
                connection.Open();
                command.Parameters.AddWithValue("@name", Database);
                command.Parameters.AddWithValue("@path", restoreFile);
                command.ExecuteNonQuery();
                connection.Close();
            }
            return true;
        }
    }
}


第一種方法是利用庫SQLDMO來進行數據庫的備份和恢復。這種方法在恢復時,原數據不能正在使用當中,可以先把原數據庫刪除,適用于數據庫誤刪除或者sql server數據庫軟件重裝的情況下進行.當然這種情況下,發布時,必須把庫SQLDMO打包。

 

第二種方式是通過調用sql指令來完成數據庫的備份和還原。這種方法在恢復時,原數據必須存在,恢復時覆蓋掉原數據庫的數據。

 

備份的情況當然是數據庫必須存在而且已經附加到數據庫管理器中。

 

可以根據需要采用這兩種方式


該文章在 2018/1/30 23:58:43 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved