Kerry White Kerry White - 4 months ago 15
MySQL Question

C# and MySQL Command - two different syles?

So, after many hours of learning MySQL and trying to get my code to work. I have found at least two different ways to set up the SQL Command. From that, I have, hopefully, a general question in MySQL using C#.

What is the difference between these two Commands:

MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;


and

MySqlCommand cmd;
cmd = conn.CreateCommand();
cmd.Connection = conn;


Is one preferred over the other?

I've ran both and both seem to work fine inserting data in my db table. I don't know if it'll help answer it, but here's my code:

public static void AddSong(Songs s)
{
MySqlConnection conn;
string myConnectionString;

myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=mysql;database=MySQL_TestDB;";

conn = new MySqlConnection();
conn.ConnectionString = myConnectionString;

try
{
conn.Open();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}


string query = "INSERT INTO Songs (Title, Artist) VALUES (" +
"@Title, " +
"@Artist)";

/*
MySqlCommand cmd;
cmd = conn.CreateCommand();
cmd.Connection = conn;
*/

MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = query;

cmd.Parameters.AddWithValue("@Title", s.Name);
cmd.Parameters.AddWithValue("@Artist", s.Artist);
cmd.ExecuteNonQuery();

conn.Close();
}

Answer

NO, AFAIK they both are same and does the same thing. conn.CreateCommand() actually returns a new MySqlCommand instance.

As the Documentation clearly says

Creates and returns a SqlCommand object associated with the SqlConnection.