1.首先在项目中加入 SQL Server 管理对象 Interop.SQLDMO.dll 的引用(它是一个COM组件,名称是Microsoft SQLDMO Object Library)
2.创建一个类对它操作,实现两个方法(备份和恢复)
using System;
namespace maxclient
{
?///
??///
?}
}
3.还要在本地master数据库创建一个存储过程用于在恢复时杀死所有访问要恢复数据库的进程
CREATE? PROCEDURE sp_KillThread? @dbname? varchar(20)
as
begin
declare? @sql? nvarchar(500),@temp varchar(1000)
declare? @spid? int
set? @sql='declare? getspid? cursor? for
select? spid? from? master..sysprocesses? where? dbid=db_id('''+@dbname+''')'?
exec? (@sql)??
open? getspid??
fetch? next? from? getspid? into? @spid
while? @@fetch_status <> -1
begin
? set @temp='kill? '+rtrim(@spid)
? exec(@temp)
fetch? next? from? getspid? into? @spid
end
close? getspid
deallocate? getspid
end
GO
4.备份与恢复操作:
private void Button1_Click(object sender, System.EventArgs e)
??{
???try
???{
????string path=this.File1.Value;//备份到...
????string ret=DBOperater.DbBackup(t_server.Text,t_user.Text,Password1.Value,t_db.Text,t_fileName.Text,@path);
????this.Label1.Text=ret;
???}
???catch(Exception ex)
???{
????this.Label1.Text=ex.Message;
???}
??}
??private void Button2_Click(object sender, System.EventArgs e)
??{
???string path=this.File1.Value;//恢复文件路径
???//杀死所有访问该数据库的进程
???string conStr="data source=localhost;database=master;user id=sa;password=password";
???SqlConnection con=new SqlConnection(conStr);
???string cmdText=String.Format("EXEC sp_KillThread @dbname='{0}'",t_db.Text);
???SqlCommand com=new SqlCommand(cmdText,con);
???try
???{
????con.Open();
????com.ExecuteNonQuery();
????con.Close();
????//恢复数据库
????string ret=DBOperater.DbRestore(t_server.Text,t_user.Text,Password1.Value,t_db.Text,path);
??????????????? this.Label1.Text=ret;
???}
???catch(Exception ex)
???{
????con.Close();
????this.Label1.Text=ex.Message;
???}
???
??}
//*********
本程序只能恢复本地备份的db或者,于本地sqlserver安装路径相同的其他机器的备份.