Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and MySQL Command - two different syles?

Tags:

c#

mysql

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();   
    }
like image 840
Kerry White Avatar asked Feb 12 '26 11:02

Kerry White


1 Answers

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.

like image 176
Rahul Avatar answered Feb 14 '26 18:02

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!