DBController心得之一:利用DMO对象对SQL2005数据库进行Backup和restore的操作

这个礼拜没有甚么事情,所以使用C#写了一个对数据库进行backup,restore的工具DBController,学到和温习了不少东西:
1。对数据库利用sqlDMO进行宏观的操作。
2。如何利用notifyIcon控件编写sys stray的代码。
3。ListView的使用。
4。contextMenu的使用。
5。C#的委托机制,delegate
6。进度调progressBar的使用。
7。C#对windows 脚本,存储过程的调用
。。。。。。。。
今天是第一篇笔记,当中DMO的使用主要来自
TerryLee的 如何用SQLDMO在ASP.NET页面下实现数据库的备份与恢复
 
 1。得到数据库中tables的列表
 /// <summary>
  /// get the database in SqlServer 遍历数据库,得到talbe的列表
  /// </summary>
  public string[] GetSqlServerDatabases()
  {
   try
   {
    SqlConnection mySqlCon =  new SqlConnection("server=" + myServer + ";uid=" + myUser + ";pwd=" + myPassword + ";database=" + "");
    SqlCommand mySqlCmd = new SqlCommand("sp_databases",mySqlCon);
    
    mySqlCon.Open();
                ArrayList myDataBaseList = new ArrayList();
                ///*****************************************used SqlDataReader method,readOnly
                //SqlDataReader mySqlRdr = mySqlCmd.ExecuteReader();
                ////clear the former string[]
                //while(mySqlRdr.Read())
                //{
                //    myDataBaseList.Add(mySqlRdr["DATABASE_NAME"].ToString());
                //}
                //mySqlRdr.Close();
                //mySqlCon.Dispose();
                ///*****************************************used SqlDataReader method,readOnly
                SqlDataAdapter mySqlAdt = new SqlDataAdapter("sp_databases", mySqlCon);
                DataSet myDS = new DataSet();
                mySqlAdt.Fill(myDS,"DATABASE_NAME");
                mySqlCon.Close();
                foreach (DataRow row in myDS.Tables["DATABASE_NAME"].Rows)
                {
                    myDataBaseList.Add(row[0].ToString());
                }
    String[] myArr = (String[]) myDataBaseList.ToArray( typeof( string ) );
    return myArr;//myDataBaseList;
   }
   catch(Exception e)
   {
                throw e;    
   }
  }
2。进行对数据库的备份,
        /// <summary>
        /// Backup DB.
        /// </summary>
        public bool backupDB(string targetFile, string toBackup)
  {
            SQLDMO.Backup objBackup = new SQLDMO.BackupClass();
            SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
            try
            {
                oSQLServer.LoginSecure = false;
                oSQLServer.Connect(myServer, myUser, myPassword);
                objBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                objBackup.Database = toBackup;                      //Gets or sets the database on which the backup or restore operation runs.
                objBackup.Files = targetFile;                        //指定备份的物理文件
                objBackup.BackupSetName = toBackup;                 //Gets or sets the name used to identify a particular backup set.
                objBackup.BackupSetDescription = "数据库备份Backup DB";
                objBackup.Initialize = true;
                //回调Step进行进度条的处理
                SQLDMO.BackupSink_PercentCompleteEventHandler pcech = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
                objBackup.PercentComplete += pcech;
                objBackup.SQLBackup(oSQLServer);
                return true;
            }
            catch (Exception e)
            {
                status = e.ToString();
                throw e;
            }
            finally
            {
                oSQLServer.DisConnect();
            }   
  }
 
3。进行数据库的还原操作
        /// <summary>
        /// 进行数据库的还原操作
        /// </summary>
        /// <param name="toRestore"></param>
        /// <param name="targetFile"></param>
        /// <returns></returns>
  public bool restoreDB(string toRestore,string targetFile)
  {
            if (!File.Exists(targetFile))
                return false;
             if(exepro(toRestore)!=true )//执行存储过程
            {
                 return false;
             }
            else
            {
                SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
                SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
                try
                {
                    exepro(toRestore);
                    oSQLServer.LoginSecure = false;
                    oSQLServer.Connect(myServer, myUser, myPassword);
                    oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
                    oRestore.Database = toRestore;
                    /**////自行修改
                    oRestore.Files = targetFile;
                    oRestore.FileNumber = 1;
                    oRestore.ReplaceDatabase = true;
                    oRestore.SQLRestore(oSQLServer);
                    return true;
                }
                catch(Exception e)
                {
                    throw e;
                }
                finally
                {
                    oSQLServer.DisConnect();
                }
            }
  }
 
4。杀死调用当前库的所有进程
        /// <summary>
        /// 杀死调用当前库的所有进程
        /// </summary>
        /// <returns></returns>
        private bool exepro(string toRestore)
        {
            SqlConnection conn = new SqlConnection("server=" + myServer + ";uid=" + myUser + ";pwd=" + myPassword + ";database=" + "");
            SqlCommand cmd = new SqlCommand("killspid",conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@dbname", toRestore);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
5。当中的killspid为存储过程,代码如下:
create proc p_killspid
@dbname varchar(200) --要关闭进程的数据库名
as
declare @sql nvarchar(500)
declare @spid nvarchar(20)
declare #tb cursor for
select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname)
open #tb
fetch next from #tb into @spid
while @@fetch_status=0
begin
exec('kill '+@spid)
fetch next from #tb into @spid
end
close #tb
deallocate #tb
go

你可能感兴趣的:(数据库,backup,restore,sql2005,DBController)