Click here to Skip to main content
15,904,023 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a .sql file (Script) containing mysql command like insert.
How can i run this .sql file from asp.net??

For ex: state.sql

INSERT INTO `state1`
(`state_id`,`state_name`,`dstatus`)
VALUES
(1,'aa',0),
(2,'bb',1),
(3,'cc',0),
(4,'dd',0),
(5,'ee',1),
(6,'ff',0),
(7,NULL,0),
(8,'dd',NULL),
(9,NULL,NULL),
(10,'ff',NULL),
(11,NULL,NULL);

My file contains thousands of records...

Can any one help..
Posted

1 solution

You need to specify file name and then first read it's content in a string and then execute CommandText command.

PS: this will work as long you don't have GO statement in your sql script.

Since SQL Server 2005, one can use smo library to do this operation and not use batch command and osql connection as previously. Here is how to do it:
C#
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string sqlConnectionString = "Data Source=(local);
                 Initial Catalog=AdventureWorks;Integrated Security=True";
            FileInfo file = new FileInfo("C:\\myscript.sql"); 
            string script = file.OpenText().ReadToEnd(); 
            SqlConnection conn = new SqlConnection(sqlConnectionString); 
            Server server = new Server(new ServerConnection(conn)); 
            server.ConnectionContext.ExecuteNonQuery(script);
        }
    }
}

Refer:
Run a .sql script files in C# [^]
C#: Executing batch T-SQL Scripts containing GO statements[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900