在這裡我通過在程式中把sql server資料庫安裝到客戶的機器上去:在還原資料前先檢查是否有該資料庫,如果有,可以刪除,也可以殺掉該資料庫相關進程。然後再執行還原作業。
Code
public class DatabaseOper
{
public DataOperateBase _Oper;//資料庫操作類對象
public DatabaseOper()
{
_Oper = new SqlDataOperate();
//WebConfig 為定義類
_Oper.ConnectionString = WebConfig.getMasterConn();//初始化串連
}
/// <summary>
/// 備份/恢複
/// </summary>
/// <param name="Type">操作類型,1為備份,2為恢複</param>
/// <param name="FilePath">路徑,如D:\Bak\Bak.bak</param>
/// <returns></returns>
protected bool DatabaseBak(int Type, string FilePath)
{
bool ReturnData = false;
string dbName;
string sqlText = string.Empty;
SqlConnection con = new SqlConnection();
con.ConnectionString = WebConfig.getConnStr();
dbName = con.Database;
if (Type == 1)
{
sqlText = "backup database "+ dbName +" to disk ='" + FilePath + "' with init";
}
else if (Type == 2)
{
if (ExistsDB(dbName))
{
killProc(dbName);
}
sqlText = "restore database "+dbName+" from disk = '" + FilePath + "'";
}
try
{
_Oper.ExecSql(sqlText);
ReturnData = true;
}
catch(SqlException sqlEx) {
throw (sqlEx);
}
return ReturnData;
}
}
/// <summary>
/// 判斷資料庫是否存在
/// </summary>
/// <param name="dbName">資料庫名稱</param>
/// <returns></returns>
private bool ExistsDB(string dbName)
{
bool exist = false;
string sqlText = "if not exists(select * from master..sysdatabases where name='" + dbName + "') select getdate() else select null";
DataTable dt;
_Oper.ConnectionString = WebConfig.getMasterConn();
_Oper.ExecSql(sqlText, out dt);
if (dt.Rows[0][0]== Convert.DBNull)
{
exist = true;
}
return exist;
}
/// <summary>
/// 殺掉資料庫進程
/// </summary>
/// <param name="dbName">要殺掉進程的資料庫名</param>
private void killProc(string dbName)
{
_Oper.AddParameter("@dbname", dbName);
try
{
_Oper.ExecProc("killspid");//預存程序很多地方都有,到網上找
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
}