.NET 應用通過 System.Diagnostics.Process 啟動 cmd.exe,執行 exp/imp 命令行工具,實現遠程數據庫備份還原自動化。
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/touser | Schema 重映射導入 |
tables=... | 表級導出/導入 |
query=... | 導出時附加 WHERE 條件 |
buffer/recordlength | 調優大數據量導出性能 |
StandardOutput/StandardError 寫入文件/數據庫,便於審計與故障排查。imp ... show=y 驗證備份文件完整性;或校驗 exp 日誌中的 "successfully terminated" 關鍵字。Data Pump (expdp/impdp),性能更強、支持並行、網絡模式、細粒度過濾,.NET 調用方式同理。file="D:\Backup\My DB.dmp"。parfile。ORACLE_HOME/PATH 未配置導致 exp 找不到。