[英]Best practices for executing SQL Server Scripts from a .NET Application?
從.NET應用程序中執行SQL Server腳本的推薦方法是什么?為什么?
我正在創建一個應用程序,我們可以從我們的安裝程序運行,以便在安裝我們的應用程序的早期版本時處理數據庫的升級。 數據庫有一個版本表,我可以以編程方式訪問並確定要運行哪些升級腳本以升級數據庫。 我將它嵌入到我們的安裝程序可以調用以進行升級的應用程序中是有意義的。
我正在尋找如何最好地執行適當的升級腳本。 在網上搜索我已經看到了通過“GO”語句拆分腳本並使用SqlCommand.ExecuteNonQuery()的建議 。 我也看到了使用SQL Server管理對象(SMO)的建議 。
我正在尋找有關從.NET應用程序中執行這些腳本的各種方法的優缺點的建議。
我使用System.Diagnostics.Process並調用OSQL.exe獲得了一致的結果。 它為sql文件....
我創建了一個臨時文件,我寫了我的嵌入式sql文件,OSQL執行它,然后清理它。
process.StartInfo = new System.Diagnostics.ProcessStartInfo();
process.StartInfo.FileName = OSQLpath;
process.StartInfo.UseShellExecute = false;
...
if (!System.IO.Directory.Exists(workingDirectory))
System.IO.Directory.CreateDirectory(workingDirectory);
...
StringBuilder sbArgs = new StringBuilder();
sbArgs.Append("-S ").Append(_serverName);
sbArgs.Append(" -d ").Append(_databaseName);
sbArgs.Append(" -E");
sbArgs.Append(" -i ").Append("\"").Append(inputSQLFilePath).Append("\""); // input file
sbArgs.Append(" -o ").Append("\"").Append(System.IO.Path.Combine(workingDirectory, String.Format("osqloutput_{1}_{0}.txt", fileUnique, fileName))).Append("\""); // output file
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.Arguments = sbArgs.ToString();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
...
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
process.Start();
process.WaitForExit();
最好的方法是滿足所有功能和非功能限制的任何方法。
您需要什么樣的速度,當前情況是否有任何問題您的備份/故障策略是什么?
我可能會使用SqlCommand.ExecuteNonQuery(),因為它是.net運行時的一部分,不需要額外安裝用戶可能不需要的應用程序。
根據您的問題,我假設存在一個包含大量嵌入式查詢字符串的現有應用程序。 我會嘗試進入一種自動將它們放在服務器上(作為存儲過程)和代碼內部的存儲庫。
不要害怕簡單的文本文件或帶有查詢的其他配置文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.