利用SQLDMO对数据库进行备份与还原
注意(SQLDOM必须运行在SQL Server SP2或以上版本)
//备份数据库
private void BeginBackUp(string FileName,string uid,string pwd)
{
string Path =FileName;
//实例化SQLDMO的各个对象
SQLDMO.Backup backup = new SQLDMO.BackupClass();
SQLDMO.SQLServer server = new SQLDMO.SQLServerClass();
try
{
//设置安全验证
server.LoginSecure=false;
//设置连接数据库
server.Connect("(local)",uid,pwd);
backup.Action=0;
//方法绑定
SQLDMO.BackupSink_PercentCompleteEventHandler percent = new SQLDMO.BackupSink_PercentCompleteEventHandler(ShowProcessBar);
backup.PercentComplete +=percent;
//设置备份的数据库
backup.Database="LibraryClass";
//设置备份文件名
backup.BackupSetName="LibraryClassbackup";
//设置备份文件描述
backup.BackupSetDescription="BackUp";
Path = Path + backup.BackupSetName.ToString() ;
//设置存储路径
backup.Files=@Path;
backup.Initialize=true;
//设置备份服务器--与server关联
backup.SQLBackup(server);
MessageBox.Show("备份成功!");
catch(Exception ex)
{
MessageBox.Show("备份失败,请检查!" +"\n" + ex.Message.ToString() );
}
finally
{
//释放对象
server.DisConnect();
server=null;
backup=null;
}
}
private void ShowProcessBar(string message,int percent)
{
//显示进度条
this.pbProcess.Value=percent;
}
//还原数据库
//实例SQLDMO还原对象
private void RealeaseBD(string FileName,string uid,string pwd)
{
SQLDMO.Restore restore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer server = new SQLDMO.SQLServerClass();
try
{
server.LoginSecure=false;
//设置连接数据库
server.Connect("(local)",uid,pwd);
//触发还原数据库方法
SQLDMO.RestoreSink_PercentCompleteEventHandler percent = new SQLDMO.RestoreSink_PercentCompleteEventHandler(Show);
restore.PercentComplete +=percent;
restore.Action =SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
//设置需还原的数据库
restore.Database="LibraryClass";
//备份文件存放路径
restore.Files=FileName
restore.ReplaceDatabase=true;
restore.FileNumber=1;
//设置还原服务器
restore.SQLRestore(server);
MessageBox.Show("还原成功!");
}
//异常处理
catch(Exception ex)
{
MessageBox.Show("还原数据库出错" + "\n" + ex.Message);
}
//释放对象
finally
{
server.DisConnect();
restore=null;
server=null;
}
}
private void Show(string Message,int percent)
{
this.pBarProcess.Value=percent;
}