在網上搜索了找到了小白的Blog上轉了一個大富翁論壇上的討論,看了討論後發現裡面提供的方法還不能直接用於ASP.Net。我對代碼進行了稍稍的改動
void restoreButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;
string restoreSql = "use master;";
restoreSql += "restore database @dbname from disk = @path;";
string pai = "use master;ALTER DATABASE Wy SET OFFLINE WITH ROLLBACK IMMEDIATE;ALTER DATABASE Wy SET ONLINE WITH ROLLBACK IMMEDIATE";
SqlConnection conn = new SqlConnection(ConnStr);
SqlCommand com1 = new SqlCommand(pai, conn);
SqlCommand myCommand = new SqlCommand(restoreSql, new SqlConnection(ConnStr));
myCommand.Parameters.Add("@dbname", SqlDbType.Char);
myCommand.Parameters["@dbname"].Value = dbname;
myCommand.Parameters.Add("@path", SqlDbType.Char);
myCommand.Parameters["@path"].Value = path;
try
{
conn.Open();
com1.ExecuteNonQuery();
conn.Close();
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
infoLabel.Text = "恢復成功!
已經把備份"+path+"恢復到數據庫";
}
catch(Exception ex)
{
infoLabel.Text = "恢復失敗!
出錯信息如下:
" + ex.ToString();
}
finally
{
myCommand.Connection.Close();
}
}