JYelton
JYelton

Reputation: 36512

Which prefix should I use for MySql named parameters in C# using Connector/Net?

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:

Adding parameters:

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).

Questions:

Upvotes: 5

Views: 2422

Answers (1)

Gaurav Joseph
Gaurav Joseph

Reputation: 946

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.

enter image description here

Upvotes: 8

Related Questions