Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MySQL Parameters : ? or @

Tags:

c#

mysql

I'm kind of confused with the MySQL parameters.

Both of the following parts of my code work fine. The first one uses parameters with @ :

const string query = "UPDATE `items` SET `name` = @name, `price` = @price WHERE `id` = @id";
try
{
    using (MySqlCommand cmd = new MySqlCommand(query, Database.MyConnection))
    {
        cmd.Parameters.AddWithValue("name", name);
        cmd.Parameters.AddWithValue("price", price);
        cmd.Parameters.AddWithValue("id", id);
        cmd.ExecuteNonQuery();
    }
}

Second uses parameters with ? :

const string query = "UPDATE `items` SET `name` = ?name, `price` = ?price WHERE `id` = ?id";
try
{
    using (MySqlCommand cmd = new MySqlCommand(query, Database.MyConnection))
    {
        cmd.Parameters.AddWithValue("name", name);
        cmd.Parameters.AddWithValue("price", price);
        cmd.Parameters.AddWithValue("id", id);
        cmd.ExecuteNonQuery();
    }
}

These answers say both @ or ? work fine. Even cmd.Parameters.AddWithValue("@name", name); seems to work (note the @ in the name).

  1. Why all of them work fine with MySQL ?

  2. Is there a difference between them ?

  3. Which one is the proper way to use with MySQL ?

Thanks for any help I'll get.

like image 688
Gabriel L. Avatar asked Mar 21 '23 22:03

Gabriel L.


1 Answers

From the documentation:

Prior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL. To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL.

like image 95
CodeCaster Avatar answered Mar 31 '23 14:03

CodeCaster