使用C#執行.SQL腳本檔
本文介紹幾種在C#中執行.SQL檔案的方法,建議使用Microsoft的SQL Server Management Objects (SMO)。
使用SMO的實作:
匯入以下命名空間:
<code class="language-csharp">using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Common;</code>
建立與SQL Server資料庫的連線:
<code class="language-csharp">string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YourDatabaseName;Data Source=YourSQLServerName"; SqlConnection conn = new SqlConnection(sqlConnectionString);</code>
建立一個Server物件來表示SQL Server:
<code class="language-csharp">Server server = new Server(new ServerConnection(conn));</code>
執行.SQL腳本:
<code class="language-csharp">string script = File.ReadAllText(@"Path\To\Your.sql"); server.ConnectionContext.ExecuteNonQuery(script);</code>
程式碼範例:
<code class="language-csharp">using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Common; using System.IO; public partial class ExcuteScript : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YourDatabaseName;Data Source=YourSQLServerName"; string script = File.ReadAllText(@"Path\To\Your.sql"); SqlConnection conn = new SqlConnection(sqlConnectionString); Server server = new Server(new ServerConnection(conn)); server.ConnectionContext.ExecuteNonQuery(script); } }</code>
注意:
server.ConnectionContext.ExecuteWithResults(script)
來取代ExecuteNonQuery
。 以上是如何使用 C# 執行 .SQL 腳本檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!