Search code examples
c#mysqlscriptingexecute

How to create a piece of C#.NET script to let MySql server execute a MySql Script?


Suppose I have a myTest.sql scripts, which contains thousands of "create table blahblah" statements.

myTest.sql :

 CREATE TABLE A;
 CREATE TABLE A1;
 ....
 CREATE TABLE A1000;

What Im trying to achieve is that make an C# script to force MySql server EXECUTE the myTest.sql file, instead of doing

  using (MySqlConnection cn = new MySqlConnection(ConectionString))
  {
    MySqlCommand newCmd = new MySqlCommand("create statement here 1", cn);
    cn.Open();
    newCmd.ExecuteNonQuery();
    cn.Close();
  }     

I dont want to repeat 1000 times or a for loop something like that. Thanks for all helps and please forgive my grammar problems.


Solution

  • Could you load the myTest.sql file into a string and pass it to the MySqlCommand.

    string myTestSql = IO.File.ReadAllText("myTest.sql");
    ...
    MySqlCommand newCmd = new MySqlCommand(myTestSql, cn);
    

    Should work as long as MySQL accepts commands separated by semicolons.