Night Walker
Night Walker

Reputation: 21270

Why do I get "You have an error in your SQL Syntax" when I pass parameters into MySqlParameter?

I am getting following exception with my code

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 ''MachineSimulator'' 

var sqlParams = new[]
                                            {
                                                new MySqlParameter("@MachineSimulatorDb",GlobalVariables.MachineSimulatorDb),
                                                new MySqlParameter("@CAMXMassagesTable" ,GlobalVariables.CamxmassagesTable)
                                            };

            using (var conn = new MySqlConnection(GlobalVariables.ConnectionString))
            {
                conn.Open();
                using(var command = new MySqlCommand())
                {
                    command.Connection = conn;
                    command.Parameters.AddRange(sqlParams);

                    command.CommandText = "CREATE DATABASE IF NOT EXISTS @MachineSimulatorDb;";

                    command.ExecuteNonQuery();


                }


            }

Any idea what is wrong there ?

Thanks

Upvotes: 0

Views: 427

Answers (2)

user610650
user610650

Reputation:

When I used MySqlParameter, it was working with a ? character, not with the @ character. This might your problem here; eg:

new MySqlParameter("?MachineSimulatorDb");

But Andomar is probably correct that you can't use a MySqlParameter to feed the name of the new database.

Upvotes: 0

Andomar
Andomar

Reputation: 238086

MySQL probably doesn't allow you to pass a parameter to create database. Try:

command.CommandText = string.Format("CREATE DATABASE IF NOT EXISTS `{0}`",  
    GlobalVariables.MachineSimulatorDb);

If the variables you use come from an usafe source, you should be aware of the danger of SQL Injection.

Upvotes: 3

Related Questions