NinetyNine's Treasure

| 积淀*育创新 智慧创造价值|

导航

数据库的还原与备份

Posted on 2007-08-07 00:24  (NineTyNine)  阅读(964)  评论(1)    收藏  举报
*****************************************数据库备份******************************************
方法一:(需引用sqldmo.dll)
public static void DbBackup()
{
    SQLDMO.Backup oBackup 
= new SQLDMO.BackupClass();
    SQLDMO.SQLServer oSQLServer 
= new SQLDMO.SQLServerClass();
    
try
    
{
        oSQLServer.LoginSecure 
= false;
        oSQLServer.Connect(
"localhost""sa""1234");
        oBackup.Action 
= SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
        oBackup.Database 
= "Northwind";
        oBackup.Files 
= @"d:\Northwind.bak";
        oBackup.BackupSetName 
= "Northwind";
        oBackup.BackupSetDescription 
= "数据库备份";
        oBackup.Initialize 
= true;
        oBackup.SQLBackup(oSQLServer);
    }

    
catch
    
{
        
throw;
    }

    
finally
    
{
        oSQLServer.DisConnect();
    }

}



方法二:
在事件里填写如下
SaveFileDialog sfd 
= new SaveFileDialog();
string backPath ="";
sfd.Filter
= "*.bak|*.bak|*.back|*.back" ;
sfd.InitialDirectory
=@"C:\";
sfd.FilterIndex
=1;
sfd.RestoreDirectory
=true;
if(sfd.ShowDialog()==DialogResult.OK)
{
    backPath 
= sfd.FileName.ToString();
    SqlConnection con 
=li.createCon();
    SqlCommand cmdBK 
= new SqlCommand();
    cmdBK.CommandType 
= CommandType.Text;
    cmdBK.Connection 
= con;
    cmdBK.CommandText 
= @"backup database GJJ to disk='"+backPath+"' with init";
    
try 
    
{
        con.Open();
        cmdBK.ExecuteNonQuery();
        MessageBox.Show(
"数据库备份成功","数据库备份",MessageBoxButtons.OK,MessageBoxIcon.Warning);
    }

    
catch(Exception ex) 
    
{
        MessageBox.Show(ex.Message);
    }

    
finally
    
{
        con.Close();
        con.Dispose();
    }

}
*********************************************数据库还原***********************************************
在使用这个方法之前先引用sqldmo.dll


还原数据库

用于数据库还原的方法
        
调用killspid存储过程,杀掉进程(注意:此存储过程放在master库中,下面的连接字符串连接到此库)
***************************************************下为kill存储过程*********************************************
CREATE   proc   killspid   (@dbname   varchar(20))   
as   
begin   
    declare   @sql   nvarchar(
500)   
    declare   @spid   
int--SPID   值是当用户进行连接时指派给该连接的一个唯一的整数   
    
set   @sql='declare getspid cursor for select   spid   from   sysprocesses   where   dbid=db_id('''+@dbname+''')'   
    
--sysprocesses   包含有关   SQL   Server   进程的信息。   
    exec   (@sql)   

    open   getspid   
    
    fetch   next   from   getspid   into   @spid   
    
while   @@fetch_status<>-1--如果FETCH   语句没有执行失败或此行不在结果集中。   
    begin   
        exec(
'kill   '+@spid)--终止正常连接   
        fetch   next   from   getspid   into   @spid   
    end   
    close   getspid   
    deallocate   getspid   
end  
NinetyNine参考网络兼部分原创