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

.NET 程式遠程調用 EXP/IMP 實現 Oracle 數據庫備份與還原

     編輯:Oracle 資料庫基礎

架構思路

.NET 應用通過 System.Diagnostics.Process 啟動 cmd.exe,執行 exp/imp 命令行工具,實現遠程數據庫備份還原自動化。

核心代碼 (C#)

string dmpFile = "DATABASE.dmp";
string logFile = "DATABASE.log";
string user = "USRID";
string pwd = "USRPWD";
string tns = "TNS";  // tnsnames.ora 中的服務名

// exp 命令:導出整個用戶對象
string cmd = $"exp {user}/{pwd}@{tns} file={dmpFile} log={logFile}";

Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;

try {
    p.Start();
    p.StandardInput.WriteLine(cmd);
    p.StandardInput.WriteLine("exit");
    // string output = p.StandardOutput.ReadToEnd(); // 可選讀取輸出
    p.WaitForExit(); // 等待進程結束

    int exitCode = p.ExitCode;
    if (exitCode == 0) {
        lblMsg.Text = "提示:數據庫備份成功!";
    } else {
        string err = p.StandardError.ReadToEnd();
        lblMsg.Text = $"提示:數據庫備份失敗!ExitCode={exitCode}, Error={err}";
    }
} catch (Exception ex) {
    lblMsg.Text = "提示:數據庫備份異常!" + ex.Message;
} finally {
    p.Close();
}

// 前端彈窗提示(WebForms)
ClientScript.RegisterStartupScript(this.GetType(), "alert", $"alert('{lblMsg.Text}');", true);

還原 代碼調整

// imp 命令:從 dmp 文件導入,忽略創建錯誤
string impCmd = $"imp {user}/{pwd}@{tns} file={dmpFile} log={logFile} ignore=y full=y";

關鍵參數說明

參數含義
ignore=y對象已存在時忽略錯誤,繼續導入數據
full=y導入整個導出文件(需 DBA/IMP_FULL_DATABASE 權限)
fromuser/touserSchema 重映射導入
tables=...表級導出/導入
query=...導出時附加 WHERE 條件
buffer/recordlength調優大數據量導出性能

生產環境強化建議

  1. 異步執行:備份/還原耗時長,應放入後台任務佇列(Hangfire、Quartz、Windows Service),避免阻塞 Web 請求。
  2. 日誌持久化:將 StandardOutput/StandardError 寫入文件/數據庫,便於審計與故障排查。
  3. 權限最小化:運行進程的服務賬號僅具備讀寫備份目錄、調用 exp/imp 的權限,不具備系統管理員權限。
  4. 並發控制:同一時間僅允許一個備份/還原任務,防止 exp/imp 互斥衝突。
  5. 備份驗證:定期執行 imp ... show=y 驗證備份文件完整性;或校驗 exp 日誌中的 "successfully terminated" 關鍵字。
  6. 替代方案:Oracle 11g+ 推薦使用 Data Pump (expdp/impdp),性能更強、支持並行、網絡模式、細粒度過濾,.NET 調用方式同理。

常見坑點

  • 路徑含空格需雙引號包裹:file="D:\Backup\My DB.dmp"。
  • 密碼含特殊字符(@、#、$、!)需在命令行轉義或使用參數文件 parfile。
  • Oracle Client 未安裝或 ORACLE_HOME/PATH 未配置導致 exp 找不到。
  • 防火牆阻攔 1521 端口或 TNS 解析失敗。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved