Question

I have C# code that cycles through .sql files and executes what's inside them to set up a database.

One .sql file is basically as follows:

DROP PROCEDURE IF EXISTS myProc;

DELIMITER $$

CREATE PROCEDURE myProc()
BEGIN
-- procedure stuff goes here
END $$

DELIMITER ;

CALL myProc();

When I input this into the MySQL Query Browser's script window, it runs perfectly... over and over again, just as one would want it to.

However, if I put the string into my IDbCommand and execute it...

connection.Open(); // An IDbConnection
IDbTransaction transaction = connection.BeginTransaction();
using (IDbCommand cmd = connection.CreateCommand())
{
    cmd.Connection = connection;
    cmd.Transaction = transaction;
    cmd.CommandText = line;
    cmd.CommandType = CommandType.Text;

    try
    {
        cmd.ExecuteNonQuery();
    }
    catch (SqlException ex)
    {
        transaction.Rollback();
        return false;
    }
}

transaction.Commit();
connection.Close();

... I get the dreaded exception 1064...

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER $$ CREATE PROCEDURE myProc() BEGIN...

So, the question is... why does MySQL let me do this with no problems, but when I try to run it from C#, it fails? And of course the second question is how I'm supposed to fix it.

Was it helpful?

Solution

OTHER TIPS

For those looking for a quick snippet...

var connectionString = @"server=ChangeMe;user=ChangeMe;pwd=ChangeMe;database=ChangeMe;"; 

var scriptText = File.ReadAllText(@"C:\script.sql");

using (var connection = new MySqlConnection(connectionString))
{
    var script = new MySqlScript(connection, scriptText);
    connection.Open();
    script.Execute();
}  

Some of the commands in your script are interpreted bt the mysqlk client excutable before the SQL is sent to the server.

See mysql commands

In effect all the delimiters

To interpret the script from C# you will have to write code that knows what the command is, you cannot just pass the commands line by line to the server.

e.g. you have 3 commands in that file and so want to call ExecuteNonQuery only 3 times

and from paracycle's coment you need to use the MySqlScript class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top