Home >Database >Mysql Tutorial >How Can I Execute an .SQL Script File Using C#?
Execute .SQL script file using C#
This article introduces several methods of executing .SQL files in C#. It is recommended to use Microsoft's SQL Server Management Objects (SMO).
Implementation using SMO:
Import the following namespace:
<code class="language-csharp">using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Common;</code>
Establish a connection to the SQL Server database:
<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>
Create a Server object to represent SQL Server:
<code class="language-csharp">Server server = new Server(new ServerConnection(conn));</code>
Execute .SQL script:
<code class="language-csharp">string script = File.ReadAllText(@"Path\To\Your.sql"); server.ConnectionContext.ExecuteNonQuery(script);</code>
Code example:
<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>
Note:
server.ConnectionContext.ExecuteWithResults(script)
instead of ExecuteNonQuery
. The above is the detailed content of How Can I Execute an .SQL Script File Using C#?. For more information, please follow other related articles on the PHP Chinese website!