Run a .sql script files in C#

Hi friend 


Here i am writing the code which is used to execute .sql script file from any location used to create database.
 for this we need to use some namespace like,System.Data.SqlClient, using System.IO, Microsoft.SqlServer.Management.Common, Microsoft.SqlServer.Management.Smo


using System.Configuration;
using System.Data;
using  System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

public partial class _1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string sqlConnectionString = @"Data Source=PS135\SQLEXPRESS;Initial Catalog=Dummy;Integrated Security=True;";  //this is a connection  string use to connect with database .

        FileInfo file = new FileInfo("C:\\Dummy.sql"); //Location of the .sql file

        string script = file.OpenText().ReadToEnd();

        SqlConnection con = new SqlConnection(sqlConnectionString);

        Server server = new Server(new ServerConnection(con));//Initializes a new instance of the ServerConnection class with the specified connection parameters.

        server.ConnectionContext.ExecuteNonQuery(script);


    }
}
 
Hope it helps you ......

0 comments: