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.
Example 1: cmd.CommandText = "UPDATE table SET thing = @value;";
Example 2: cmd.CommandText = "UPDATE table SET thing = ?value;";
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:
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).
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)
The answer to your questions:
Example 5 uses a named parameter object. The use of this is so:
cmd.CommandText = "UPDATE table SET thing = :value;";
cmd.Parameters.AddWithValue("value", user_value);
You can compare with this:
cmd.CommandText = "UPDATE table SET thing = @value;";
cmd.Parameters.AddWithValue("@value", user_value);
Notice that the '@' is not used when using the colon. Atleast, that is how it should be. It may work the other way because internally the representations would be the same.
The use of unnamed parameter is little different.
cmd.CommandText = "UPDATE table SET thing = ?;";
cmd.Parameters.AddWithValue("anyname", user_value);
The name of the parameter could most probably be anything and it would be just taken in from the index value.
While named parameters will be accessed by name the unnamed ones are used by index value, potentially assigning wrong values like this:
cmd.CommandText = "UPDATE table SET thing1 = ?, thing2 = ?;";
cmd.Parameters.AddWithValue("anyname1", user_value2);
cmd.Parameters.AddWithValue("anyname2", user_value1);
Here the 'user_value2' which should have been assigned to 'thing2' gets assigned to 'thing1' because it appears first in the index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With