views:

104

answers:

2

How to create a database using connector/net programming? How come the following doesn't work?

    string connStr = "server=localhost;user=root;port=3306;password=mysql;";
    MySqlConnection conn = new MySqlConnection(connStr);
    MySqlCommand cmd;
    string s0;

    try
    {
        conn.Open();
        s0 = "CREATE DATABASE IF NOT EXISTS `hello`;";
        cmd = new MySqlCommand(s0, conn);
        conn.Close();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
+2  A: 

You might want to execute the MySqlCommand. Now you just create one, but it doesn't execute your query.

Try this:

conn.Open();
s0 = "CREATE DATABASE IF NOT EXISTS `hello`;";
cmd = new MySqlCommand(s0, conn);
cmd.ExecuteNonQuery();
conn.Close();
Pbirkoff
+1  A: 

You need to execute the command and also make sure to properly dispose objects:

string connStr = "server=localhost;user=root;port=3306;password=mysql;";
using (var conn = new MySqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "CREATE DATABASE IF NOT EXISTS `hello`;";
    cmd.ExecuteNonQuery();
}
Darin Dimitrov