Home >Database >Mysql Tutorial >How Can I Execute an .SQL Script File Using C#?

How Can I Execute an .SQL Script File Using C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-17 09:56:10372browse

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:

  1. Import the following namespace:

    <code class="language-csharp">using Microsoft.SqlServer.Management.Smo;
    using Microsoft.SqlServer.Management.Common;</code>
  2. 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>
  3. Create a Server object to represent SQL Server:

    <code class="language-csharp">Server server = new Server(new ServerConnection(conn));</code>
  4. 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:

  • Make sure the .SQL file is properly formatted and contains valid SQL statements.
  • To capture execution output, you can use 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn