C#实现数据库的备份和还原

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using System.Data;
using System.IO;
namespace DBConection.service
{
    public class DbService
    {
        //数据库的备份
        public bool BackUPDB(string strFileName, DB db)//DB是一个维护数据库连接的连接池
        {

            using (System.Data.SqlClient.SqlConnection conn = db.GetConection())
            {

                System.Data.SqlClient.SqlCommand cmdBK = new SqlCommand();
                cmdBK.CommandType = System.Data.CommandType.Text;
                cmdBK.Connection = conn;
                cmdBK.CommandText = @"backup database " + db.GetDBName() + " to disk='" + strFileName + "' with init";
                try
                {
                    conn.Open();
                    cmdBK.ExecuteNonQuery();
                    LogServcie.Log.writeLog("数据库备份成功。/n备份地址:" + strFileName);
                    return true;
                }
                catch (Exception ex)
                {
                    LogServcie.Log.WirteErr("数据库备份失败", ex);
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();
                }
                return false;
            }

        }

        public void RestoreDB(string strDbName, string strFileName, string strToFileName, DB db)
        {


            using (System.Data.SqlClient.SqlConnection conn = db.GetConection())
            {

                DirectoryInfo dir = new DirectoryInfo(strToFileName);
                if (!dir.Exists)
                {
                    dir.Create();
                }
                string logicName = this.GetLogicName(strFileName, db);
                if (strDbName.IndexOf(".bak") != -1)
                {
                    strDbName = strDbName.Substring(0, strDbName.IndexOf(".bak"));
                }
                if (logicName != string.Empty)
                {
                    conn.Open();
                    //还原数据库
                    SqlCommand cmdRT = new SqlCommand();
                    cmdRT.CommandType = CommandType.Text;
                    cmdRT.Connection = conn;
                    cmdRT.CommandText = @"RESTORE DATABASE [" + strDbName + "] FROM  DISK = N'" + strFileName + "' WITH  FILE = 1,  NOUNLOAD ,  STATS = 10,  RECOVERY ,  MOVE N'" + logicName + "_Data' TO N'" + strToFileName + "//" + strDbName + ".mdf',  MOVE N'" + logicName + "_Log' TO N'" + strToFileName + "//" + strDbName + "_log.ldf'";

                    try
                    {
                        cmdRT.ExecuteNonQuery();
                        LogServcie.Log.writeLog("数据库还原成功。/n备份地址:" + strFileName + "/n 还原成数据库:" + strDbName);
                    }
                    catch (Exception ex)
                    {
                        LogServcie.Log.WirteErr("数据库还原失败", ex);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }

            }
        }

        /// <summary>
        /// 用一个备份文件夹来恢复所有数据
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="strToFileName"></param>
        /// <param name="logicName"></param>
        /// <param name="db"></param>
        public void RestoreDB(string[] Files, string strToFileName, DB db)
        {

            foreach (string fileName in Files)
            {
                FileInfo file = new FileInfo(fileName);
                if (file.Exists)
                    RestoreDB(file.Name, file.FullName, strToFileName, db);

            }

        }

        /// <summary>
        /// 获取数据库的逻辑名
        /// </summary>
        /// <param name="bakPath"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public string GetLogicName(string bakPath, DB db)
        {
            using (System.Data.SqlClient.SqlConnection conn = db.GetConection())
            {

                FileInfo file = new FileInfo(bakPath);
                if (file.Exists)
                {
                    conn.Open();
                    //还原数据库
                    SqlCommand cmdRT = new SqlCommand();
                    cmdRT.CommandType = CommandType.Text;
                    cmdRT.Connection = conn;
                    cmdRT.CommandText = @"restore FILELISTONLY FROM DISK ='" + bakPath + "'";

                    try
                    {
                        object ob = cmdRT.ExecuteScalar();
                        string logicName = Convert.ToString(ob);
                        logicName = logicName.Substring(0, logicName.IndexOf("_"));
                        LogServcie.Log.writeLog("获得数据库逻辑名:" + logicName);
                        return logicName;

                    }
                    catch (Exception ex)
                    {
                        LogServcie.Log.WirteErr("数据库还原失败", ex);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }

                return string.Empty;

            }

        }

 

    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值