首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

ASP.NET 實作 SQL Server 資料庫備份與還原功能:完整 C# 代碼範例與錯誤處理

     編輯:關於SqlServer

備份資料庫

string dbName = DropDownList1.SelectedValue;           // 使用者選擇的資料庫
string bakPath = TextBox1.Text.Trim() + ".bak";        // 備份檔完整路徑

string connStr = $"Server=(local);Database={dbName};Uid=sa;Pwd=;";
string sqlBackup = $"BACKUP DATABASE [{dbName}] TO DISK = '{bakPath}'";

using (SqlConnection con = new SqlConnection(connStr))
{
    con.Open();
    try
    {
        if (File.Exists(bakPath))
        {
            ClientScript.RegisterStartupScript(GetType(), "alert",
                "alert('檔案已存在,請重新輸入!');", true);
            return;
        }

        using (SqlCommand cmd = new SqlCommand(sqlBackup, con))
        {
            cmd.ExecuteNonQuery();
        }
        ClientScript.RegisterStartupScript(GetType(), "success",
            "alert('備份資料成功!');", true);
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        ClientScript.RegisterStartupScript(GetType(), "fail",
            "alert('備份資料失敗!');", true);
    }
    finally
    {
        con.Close();
    }
}

還原資料庫

string bakFile = FileUpload1.PostedFile.FileName;      // 使用者上傳的 .bak 檔
string dbName = DropDownList1.SelectedValue;

string connStr = $"Server=(local);Database={dbName};Uid=sa;Pwd=;";
string sqlRestore = $"USE MASTER; RESTORE DATABASE [{dbName}] FROM DISK = '{bakFile}'";

using (SqlConnection con = new SqlConnection(connStr))
{
    con.Open();
    try
    {
        using (SqlCommand cmd = new SqlCommand(sqlRestore, con))
        {
            cmd.ExecuteNonQuery();
        }
        ClientScript.RegisterStartupScript(GetType(), "success",
            "alert('還原資料成功!');", true);
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        ClientScript.RegisterStartupScript(GetType(), "fail",
            "alert('還原資料失敗!');", true);
    }
    finally
    {
        con.Close();
    }
}

關鍵實作細節

項目說明
連線字串使用 SqlConnection,驗證模式視環境調整 (整合驗證/帳號密碼)
備份指令BACKUP DATABASE [db] TO DISK = 'path',資料庫名加方括號防保留字衝突
還原指令必須先切換到 MASTER 資料庫 (USE MASTER),否則正在使用的資料庫無法還原
檔案上傳FileUpload 控制項取得客戶端路徑,伺服器端需具備讀取權限
錯誤處理try/catch/finally 確保連線釋放,前端用 RegisterStartupScript 彈窗通知
檔案存在檢查備份前 File.Exists 避免覆蓋,或依需求加入時間戳自動命名

安全性與部署建議

  • 生產環境嚴禁直接使用 sa 帳號,應建立最低權限的專用服務帳號 (僅 db_backupoperator/dbcreator)。
  • 備份檔路徑應位於 SQL Server 服務帳號可寫入的本機/網路共享路徑,而非 Web 伺服器路徑。
  • 大型資料庫備份/還原耗時長,建議改為非同步作業 (Background Service、Hangfire、SQL Agent Job) 避免 HTTP 逾時。
  • 前端上傳 .bak 檔需限制檔案大小、副檔名驗證、防惡意檔案上傳。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved