◆2.数据库的备份和实时进度显示代码:
public bool BackUPDB(string strDbName,string strFileName, ProgressBar pgbMain)
{
PBar = pgbMain ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
svr.Connect(ServerName,UserName,Password) ;
SQLDMO.Backup bak = new SQLDMO.BackupClass();
bak.Action = 0 ;
bak.Initialize = true ;
SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
bak.PercentComplete += pceh;
bak.Files = strFileName;
bak.Database = strDbName;
bak.SQLBackup(svr);
return true ;
}
catch(Exception err)
{
throw(new Exception("备份数据库失败"+err.Message)) ;
}
finally
{
svr.DisConnect() ;
}
}
private void Step(string message,int percent)
{
PBar.Value = percent ;
}
其中,这两个语句实现了进度的实时显示:
SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
bak.PercentComplete += pceh;
Step就是上面private void Step(string message,int percent) 的方法名称,它用来显示进度条的当前进度。
◆3.数据库的恢复和杀死进程的代码:
public bool RestoreDB(string strDbName,string strFileName, ProgressBar pgbMain)
{
PBar = pgbMain ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
svr.Connect(ServerName,UserName,Password) ;
SQLDMO.QueryResults qr = svr.EnumProcesses(-1) ;
int iColPIDNum = -1 ;
int iColDbName = -1 ;
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName) ;
if (strDBName.ToUpper() == strDbName.ToUpper())
svr.KillProcess(lPID) ;
}
SQLDMO.Restore res = new SQLDMO.RestoreClass() ;
res.Action = 0 ;
SQLDMO.RestoreSink_PercentCompleteEventHandler pceh = new SQLDMO.RestoreSink_PercentCompleteEventHandler(Step);
res.PercentComplete += pceh;
res.Files = strFileName ;
res.Database = strDbName ;
res.ReplaceDatabase = true ;
res.SQLRestore(svr) ;
return true ;
}
catch(Exception err)
{
throw(new Exception("恢复数据库失败,请关闭所有和该数据库连接的程序!"+err.Message)) ;
}
finally
{
svr.DisConnect() ;
}
}
其中这个语句取得了所有的进程列表:
SQLDMO.QueryResults qr = svr.EnumProcesses(-1) ;
下面的语句找到和要恢复数据库相关的进程并杀死:
int iColPIDNum = -1 ;
int iColDbName = -1 ;
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName) ;
if (strDBName.ToUpper() == strDbName.ToUpper())
svr.KillProcess(lPID) ;
}
以上就是数据库备份和恢复的关键代码,有了这些代码,我们实现更完善的数据库备份恢复功能也是没问题的,比如,你可以很容易的实现定时备份或按照一定的循环策略进行备份。
文章来源于领测软件测试网 https://www.ltesting.net/