使用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中文网其他相关文章!