4

I am having a problem when trying to create a database using mysql command. The code i am using is;

using (MySqlConnection con = connect_db())
{
    con.Open();

    MySqlCommand cmd = new MySqlCommand("CREATE DATABASE @name;", con);

    cmd.Parameters.AddWithValue("@name", "fancydb");

    try
    {
        cmd.ExecuteNonQuery();
    }
    catch (Exception exc)
    {                   
        return;
    }
    cmd.Dispose();
    con.Close();
    con.Dispose();
}

When I try to run this code I always get an error saying that I have an

error in mysql syntax near "fancydb"

but when I put the name in the command like: "CREATE DATABASE facnydb;" it works. Can anyone explain to me why is the error only happening when I try and use parameters?

4 Answers 4

3

The create-statement is not a data-manipulation-statement. Parameters are only allowed in such kind of operations. The create-statement ist a data-definition-statement.

Sign up to request clarification or add additional context in comments.

Comments

1

I would guess that query is executed as

CREATE DATABASE "fancydb";

which is wrong.

1 Comment

No! It will execude as CREATE DATABASE fancydb;
1

SqlCommand Parameters are supported for Data manipulation language operations not Data definition language operations.

Data manipulation language =

SELECT ... FROM ... WHERE ...
INSERT INTO ... VALUES ...
UPDATE ... SET ... WHERE ...
DELETE FROM ... WHERE ...

Data definition language =

CREATE TABLE ... 
DROP TABLE ... ;
ALTER TABLE ... ADD ... INTEGER;

1 Comment

So far the simplest answer I've seen on the topic of what you can and can't do. Cheers
0

This works:

cmd.CommandText = "exec ('CREATE DATABASE ' + @database)";
cmd.Parameters.AddWithValue("@database", restoreDB);
cmd.ExecuteNonQuery();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.