日期:2014-05-20  浏览次数:20872 次

.net下的sql数据的备份与还原
用了网上的一段代码,提示“因为数据库正在使用,所以未能获取对数据库的排他访问权”,请问如何杀死其它的连接进程,谢谢!
以下是网上的代码:
private   void   btnRestore_Click(object   sender,   System.EventArgs   e)
{

this.Cursor   =   Cursors.WaitCursor;
this.label1.Text   =   "   正在进行档案库的数据还原,这可能需要几秒到几十的时间,请稍候... ";
this.label1.Visible   =   true;
this.label1.Refresh();
this.pBar1.Visible   =   true;
//------------------------------------------------

string   fileName   =   "NorthwindBak ";
string   filePath   =   "D:NorthwindBak ";
string   remark   =   "备份测试 ";

SQLDMO.Restore   oRestore   =   new   SQLDMO.RestoreClass();
SQLDMO.SQLServer   oSQLServer   =   new   SQLDMO.SQLServerClass();
oRestore.Action   =   0   ;  
SQLDMO.RestoreSink_PercentCompleteEventHandler   pceh   =   new   SQLDMO.RestoreSink_PercentCompleteEventHandler(Step);  
oRestore.PercentComplete   +=   pceh;  
try
{
oSQLServer.Connect(Common.MySettings.SqlServerName,   "sa ",   " ");
SQLDMO.QueryResults   qr   =   oSQLServer.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()   ==   "CgRecord ".ToUpper())  
oSQLServer.KillProcess(lPID)   ;  
}  


oRestore.Action   =   SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
oRestore.Database   =   "Northwind ";
oRestore.Files   =   filePath;
oRestore.FileNumber   =   1;
oRestore.ReplaceDatabase   =   true;
oRestore.SQLRestore(oSQLServer);


}
catch(System.Exception   ex)
{
Common.ShowMsg( "数据还原失败:   "   +   ex.ToString());
}
finally
{
oSQLServer.DisConnect();
}

//------------------------------------------------
this.label1.Visible   =   false;
this.pBar1.Visible   =   false;
this.Cursor   =   Cursors.Default;
}

///   <summary>
///   显示还原进度条
///   </summary>
private   void   Step(string   message,int   percent)  
{  
this.pBar1.Value   =   percent   ;  
}


------解决方案--------------------
帮顶
------解决方案--------------------