在無法直接存取資料庫伺服器檔案系統(如虛擬主機、受限環境)時,可透過 ASP + ADO 執行 BACKUP DATABASE 將 .bak 寫入 Web 目錄,再以 ADODB.Stream 二進位串流提供下載。本文提供完整可執行代碼與安全注意事項。
<%@ Language=VBScript CodePage=65001 %>
<%
Response.Charset = "utf-8"
Session.CodePage = 65001
Response.Buffer = True
Response.Clear
' === 連線字串:請修改 UID/PWD/Data Source ===
Const CONN_STR = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=backup_user;Password=Str0ngP@ss;Data Source=192.168.1.100"
Dim conn, bkFile, sqlStr, fso
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open CONN_STR
' === 備份檔名:年月日_database.bak ===
bkFile = Server.MapPath(Year(Now) & Right("0"&Month(Now),2) & Right("0"&Day(Now),2) & "_database.bak")
' === 執行備份(WITH INIT 覆蓋同名檔) ===
sqlStr = "BACKUP DATABASE [YourDB] TO DISK='" & bkFile & "' WITH INIT, STATS=10"
On Error Resume Next
conn.Execute sqlStr
If Err.Number <> 0 Then
Response.Write "備份失敗: " & Err.Description
conn.Close
Set conn = Nothing
Response.End
End If
On Error GoTo 0
conn.Close
Set conn = Nothing
Response.Write "資料庫 [YourDB] 備份成功!
"
' === 提供下載 ===
Set fso = Server.CreateObject("Scripting.FileSystemObject")
If fso.FileExists(bkFile) Then
Response.Clear
Response.Buffer = True
Response.ContentType = "application/octet-stream"
Response.AddHeader "Content-Disposition", "attachment; filename=" & fso.GetFileName(bkFile)
Response.AddHeader "Content-Length", fso.GetFile(bkFile).Size
Dim stream
Set stream = Server.CreateObject("ADODB.Stream")
stream.Mode = 3 ' adModeReadWrite
stream.Type = 1 ' adTypeBinary
stream.Open
stream.LoadFromFile bkFile
Response.BinaryWrite stream.Read
stream.Close
Set stream = Nothing
' 可選:下載後刪除伺服器備份檔
' fso.DeleteFile bkFile
Else
Response.Write "找不到備份檔案。"
End If
Set fso = Nothing
Response.End
%>
db_backupoperator 固定資料庫角色或 sysadmin 伺服器角色。Server.MapPath 回傳 Web 根目錄下路徑,需預先授權給 SQL 服務帳號。Response.BinaryWrite 直接讀取大檔導致記憶體飆升;LoadFromFile 使用記憶體映射檔,效能佳。Response.AddHeader "Content-Disposition", "attachment; filename*=UTF-8''" & Server.URLEncode(fname) (RFC 5987)。BACKUP ... WITH ENCRYPTION。| 錯誤 | 原因 | 解決 |
|---|---|---|
| 無法開啟備份裝置 | SQL 服務帳號無寫入權限 | 授權資料夾給 SQL 服務帳號 (NT Service\MSSQLSERVER / 網域帳號) |
| 磁碟空間不足 | 備份檔過大 | 壓縮備份 WITH COMPRESSION、分條備份、清理舊檔 |
| 下載中斷/檔案損毀 | Response.Buffer/大檔記憶體問題 | 改用 ADODB.Stream 分塊讀取、啟用 IIS 動態壓縮關閉 |