上次做了个项目涉及到数据库的还原和恢复到网上找了一下是利用SQLDMO实现的只要添加SQLDMO引用就好了然后利用下边的类的方法就可以实现了
我把原作者的类扩充了一下可以自动识别nfig里 的数据库连接字符串可以通过变量设置还原恢复的信息
需要注意的时还原还原的时候问题最大了有别的用户使用数据库的时候无法还原解决办法就是在MASTER数据库中添加一个存储过程
create proc killspid (@dbname varchar())
as begin declare @sql nvarchar()
declare @spid int set @sql=declare getspid cursor for select spid from sysprocesses where dbid=db_id(+@dbname+) exec (@sql)
open getspid fetch next from getspid into @spid while @@fetch_status<> begin exec(kill +@spid)
fetch next from getspid into @spid end close getspid deallocate getspid end GO
在还原之前先执行这个存储过程需要传递dbname就是你的数据库的名字下边是类的原代码(nfig里的数据库连接字符串是constr)
using System
using SystemConfiguration
using SystemDataSqlClient
using SystemData
namespace webbase_class
{
/// <summary>
/// DbOper类主要应用SQLDMO实现对Microsoft SQL Server数据库的备份和恢复
/// </summary>
public class DbOper
{
private string server
private string uid
private string pwd
private string database
private string conn
/// <summary>
/// DbOper类的构造函数
/// </summary>
public DbOper()
{
conn=SystemConfigurationConfigurationSettingsAppSettings[constr]ToString()
server=cut(connserver=)
uid=cut(connuid=)
pwd=cut(connpwd=)
database=cut(conndatabase=)
}
public string cut(string strstring bgstring ed)
{
string sub
sub=strSubstring(strIndexOf(bg)+bgLength)
sub=subSubstring(subIndexOf())
return sub
}
/// <summary>
/// 数据库备份
/// </summary>
public bool DbBackup(string url)
{
SQLDMOBackup oBackup = new SQLDMOBackupClass()
SQLDMOSQLServer oSQLServer = new SQLDMOSQLServerClass()
try
{
oSQLServerLoginSecure = false
oSQLServerConnect(serveruid pwd)
oBackupAction = SQLDMOSQLDMO_BACKUP_TYPESQLDMOBackup_Database
oBackupDatabase = database
oBackupFiles = url//d\Northwindbak
oBackupBackupSetName = database
oBackupBackupSetDescription = 数据库备份
oBackupInitialize = true
oBackupSQLBackup(oSQLServer)
return true
}
catch
{
return false
throw
}
finally
{
oSQLServerDisConnect()
}
}
/// <summary>
/// 数据库恢复
/// </summary>
public string DbRestore(string url)
{
if(exepro()!=true)//执行存储过程
{
return 操作失败
}
else
{
SQLDMORestore oRestore = new SQLDMORestoreClass()
SQLDMOSQLServer oSQLServer = new SQLDMOSQLServerClass()
try
{
oSQLServerLoginSecure = false
oSQLServerConnect(server uid pwd)
oRestoreAction = SQLDMOSQLDMO_RESTORE_TYPESQLDMORestore_Database
oRestoreDatabase = database
oRestoreFiles = url//@d\Northwindbak
oRestoreFileNumber =
oRestoreReplaceDatabase = true
oRestoreSQLRestore(oSQLServer)
return ok
}
catch(Exception e)
{
return 恢复数据库失败
throw
}
finally
{
oSQLServerDisConnect()
}
}
} /FooterTemplate> </aspTemplateColumn> </Columns> </aspdatagrid>> </aspTemplateColumn> </Columns> </aspdatagrid>
private bool exepro()
{
SqlConnection conn = new SqlConnection(server=+server+uid=+uid+pwd=+pwd+database=master)
SqlCommand cmd = new SqlCommand(killspidconn)
cmdCommandType = CommandTypeStoredProcedure
cmdParametersAdd(@dbnameport)
try
{
connOpen()
cmdExecuteNonQuery()
return true
}
catch(Exception ex)
{
return false
}
finally
{
connClose()
}
}
}
}