码迷,mamicode.com
首页 > 数据库 > 详细

SQLSERVER SQL备份还原代码C#

时间:2018-06-15 12:48:34      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:RoCE   delete   sse   nbsp   range   arch   执行   private   color   

 public class BakDBHelper
    {

        /// <summary>
        /// 创建数据库备份
        /// </summary>
        public string CreateBackup(string dbname, string backname)
        {
            string res = "";
            //要备份的位置
            //string dbfullname = GetDbPath() + string.Format("{0}_{1}.bak", dbname, DateTime.Now.ToString("yyyyMMddhhmmss"));
            string dbfullname = GetDbPath() + backname;
            //判断文件是否存在
            if (File.Exists(dbfullname))
            {
                File.Delete(dbfullname);
                //MessageBox.Show(dbfullname + "的备份文件已经存在,请稍后再试");
            }
            try
            {
                SqlConnection con = new SqlConnection(GetConn());
                SqlCommand cmd = con.CreateCommand();
                con.Open();
                try
                {
                    cmd.CommandText = "use master";
                    cmd.ExecuteNonQuery();

                    //1. 执行备份操作
                    StringBuilder sql = new StringBuilder();
                    //sql.Append("exec master.dbo.proc_Backup @dbName,@dbFullName");

                    sql.Append(@"DECLARE @kid varchar(100)  
                    SET @kid=‘‘  
                    SELECT @kid=@kid+‘KILL ‘+CAST(spid as Varchar(10))  FROM master..sysprocesses  
                    WHERE dbid=DB_ID(@dbName)  
                    PRINT @kid  
                    EXEC(@kid);
                    backup database "+ dbname + " to disk=@dbFullName;");


                    SqlParameter[] parameters = new SqlParameter[]{
            new SqlParameter("@dbName",SqlDbType.NVarChar,200),
            new SqlParameter("@dbFullName",SqlDbType.NVarChar,200),
        };
                    parameters[0].Value = dbname;
                    parameters[1].Value = dbfullname;

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddRange(parameters);
                    cmd.CommandText = sql.ToString();
                    cmd.ExecuteNonQuery();
                    res = "备份完成";
                }
                finally
                {
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                res = "创建数据库备份出错:" + ex;
            }
            return res;
        }

        /// <summary>
        /// 还原数据库
        /// </summary>
        public string Restore(string dbname, string backname)
        {
            string res = "";
            //1.获取还原数据库和文件
            string dbFullName = GetDbPath() + backname;
            try
            {
                //2.执行还原操作
                SqlConnection con = new SqlConnection(GetConn());
                SqlCommand cmd = con.CreateCommand();
                con.Open();
                try
                {
                    cmd.CommandText = "use master";
                    cmd.ExecuteNonQuery();

                    StringBuilder sql = new StringBuilder();
                    //sql.Append("exec proc_Restore @dbFullName,@dbName");

                    sql.Append(@"--1.1修改为单用模式
                    exec(N‘ALTER DATABASE ‘+@dbName+‘ SET SINGLE_USER WITH ROLLBACK IMMEDIATE‘);
                --1.2结束链接进程
                    DECLARE @kid varchar(max)  
                    SET @kid=‘‘  
                    SELECT @kid=@kid+‘KILL ‘+CAST(spid as Varchar(10))  FROM master..sysprocesses  
                    WHERE dbid=DB_ID(@dbName)  ;
                    EXEC(@kid) ;
                --2.执行还原语句
                    restore database @dbName from  disk=@dbFullName
                    with replace  --覆盖现有的数据库
                --3.重置数据库为多用户模式
                    exec(N‘ALTER DATABASE ‘+@dbName+‘ SET MULTI_USER WITH ROLLBACK IMMEDIATE‘);");
                    SqlParameter[] parameters = new SqlParameter[]{
                new SqlParameter("@dbName",SqlDbType.NVarChar,200),
                new SqlParameter("@dbFullName",SqlDbType.NVarChar,200),
            };
                    parameters[0].Value = dbname;
                    parameters[1].Value = dbFullName;

                    cmd.CommandText = sql.ToString();
                    cmd.Parameters.AddRange(parameters);
                    cmd.ExecuteNonQuery();
                    res = "还原数据库完成";
                }
                finally
                {
                    con.Close();
                }

            }
            catch (Exception ex)
            {
                res = "还原数据库出错" + ex;
            }
            return res;
        }

        private static string GetDbPath()
        {
            return ConfigurationManager.AppSettings["bak_url"].ToString();
        }

        private static string GetConn()
        {
            return ConfigurationManager.AppSettings["bak_con"].ToString();
        }

        public int execSQLCommand(string sql)
        {
            int res;
            try
            {
                //2.执行还原操作
                SqlConnection con = new SqlConnection(GetConn());
                SqlCommand cmd = con.CreateCommand();
                con.Open();
                try
                {
                    cmd.CommandText = sql;
                    res = cmd.ExecuteNonQuery();
                }
                finally
                {
                    con.Close();
                }
            }
            catch (Exception)
            {
                return -1;
            }
            return res;
        }
    }

 

SQLSERVER SQL备份还原代码C#

标签:RoCE   delete   sse   nbsp   range   arch   执行   private   color   

原文地址:https://www.cnblogs.com/linyijia/p/9186444.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!