Click here to Skip to main content
12,760,727 members (33,668 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# ASP.NET MySQL
I have a .sql file (Script) containing mysql command like insert.
How can i run this .sql file from

For ex: state.sql

INSERT INTO `state1`

My file contains thousands of records...

Can any one help..
Posted 31-Mar-10 0:30am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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:
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)); 

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

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

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170217.1 | Last Updated 31 Mar 2010
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100