I am using Connector/Net 6.8.3 for a C# project and have been using it (or prior versions) for quite some time.
As I look through legacy code, I see several variations related to parameterized queries and have been attempting to determine what the differences are and if there's a best practice.
The query string:
Example 1:
cmd.CommandText = "UPDATE table SET thing = @value;";
Example 2:
cmd.CommandText = "UPDATE table SET thing = ?value;";
Adding parameters:
Example 3:
cmd.Parameters.AddWithValue("@value", user_value);
Example 4:
cmd.Parameters.AddWithValue("?value", user_value);
Example 5:
cmd.Parameters.AddWithValue("value", user_value);
All of these variations seem to work. I haven't been able to find in the official documentation anything that explains the difference in prefix usage (@
vs ?
). However, this devart.com page suggests the following:
- Unnamed parameters can be specified as '?' symbol.
- Named parameters are declared using ':' or '@' prefix followed by name of the parameter. Note that the name of the MySqlParameter object in the collection of the command should contain the '@' prefix if parameter in CommandText is used with the '@' prefix. If the parameter in CommandText contains the ':' prefix, the name of the MySqlParameter object in the command's collection should be used without any prefix.
The last point has some grammatical issues, but the examples shown seem to indicate that when using '@
' the statement cmd.Parameters.AddWithValue("@value", user_value);
should include the '@
' as well, but not when using ':
'.
However, in many of the functioning methods that I am reviewing, the query uses '@
' in the command text (Example 1), but not in the AddWithValue()
statement (Example 5).
Questions:
What are the potential consequences of omitting the prefix when adding a parameter? (Example 5)
Is there no reason to add a parameter name when using the '
?
' prefix, because it is intended for unnamed parameters? (Example 2)