在開發畢業設計的資料庫備份與還原頁面時,發現執行還原操作會遭遇資料庫排他性存取問題。參考網路討論後,對原始碼進行修改以適配 ASP.NET 環境。
void RestoreButton_Click(object sender, System.EventArgs e)
{
string path = PathTextBox.Text;
string dbName = DbDropDownList.SelectedValue;
string restoreSql = "USE master; RESTORE DATABASE @dbname FROM DISK = @path;";
string offlineOnlineSql = "USE master; ALTER DATABASE Wy SET OFFLINE WITH ROLLBACK IMMEDIATE; ALTER DATABASE Wy SET ONLINE WITH ROLLBACK IMMEDIATE";
using (SqlConnection conn = new SqlConnection(ConnStr))
using (SqlCommand offlineCmd = new SqlCommand(offlineOnlineSql, conn))
using (SqlCommand restoreCmd = new SqlCommand(restoreSql, new SqlConnection(ConnStr)))
{
restoreCmd.Parameters.Add("@dbname", SqlDbType.Char).Value = dbName;
restoreCmd.Parameters.Add("@path", SqlDbType.Char).Value = path;
try
{
conn.Open();
offlineCmd.ExecuteNonQuery(); // 強制離線斷開連線
conn.Close();
restoreCmd.Connection.Open();
restoreCmd.ExecuteNonQuery();
InfoLabel.Text = "恢復成功!\n已將備份 " + path + " 還原至資料庫";
}
catch (Exception ex)
{
InfoLabel.Text = "恢復失敗!\n錯誤訊息:" + ex.ToString();
}
finally
{
if (restoreCmd.Connection.State == ConnectionState.Open)
restoreCmd.Connection.Close();
}
}
}
SqlParameter 防止 SQL 注入,確保資料庫名稱與備份路徑安全傳遞。using 區塊確保連線正確釋放,避免連線洩漏。sysadmin 或 dbcreator 角色權限。