上次做了個項目,涉及到數據庫的還原和恢復,到網上找了一下,是利用SQLDMO實現的,只要添加SQLDMO引用就好了,然后利用下邊的類的方法就可以實現了。
我把原作者的類擴充了一下,可以自動識別web.config里 的數據庫連接字符串,可以通過變量設置還原恢復的信息。
需要注意的時還原,還原的時候問題最大了,有別的用戶使用數據庫的時候無法還原,解決辦法就是在MASTER數據庫中添加一個存儲過程:
create proc killspid (@dbname varchar(20))
as begin declare @sql nvarchar(500)
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<>-1 begin exec('kill '+@spid)
fetch next from getspid into @spid end close getspid deallocate getspid end GO
在還原之前先執行這個存儲過程,需要傳遞dbname,就是你的數據庫的名字。下邊是類的原代碼:(web.config里的數據庫連接字符串是constr)
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace web.base_class
...{
/**////
/// DbOper類,主要應用SQLDMO實現對Microsoft SQL Server數據庫的備份和恢復
///
public class DbOper
...{
private string server;
private string uid;
private string pwd;
private string database;
private string conn;
/**////
/// DbOper類的構造函數
///
public DbOper()
...{
conn=System.Configuration.ConfigurationSettings.AppSettings["constr"].ToString(); server=cut(conn,"server=",";");
uid=cut(conn,"uid=",";");
pwd=cut(conn,"pwd=",";");
database=cut(conn,"database=",";");
}
public string cut(string str,string bg,string ed)
...{
string sub;
sub=str.Substring(str.IndexOf(bg)+bg.Length);
sub=sub.Substring(0,sub.IndexOf(";"));
return sub;
}
/**////
/// 數據庫備份
///
public bool DbBackup(string url)
新聞熱點
疑難解答
圖片精選