Correct way of placeholders in paramaterized query from C#
-
06-06-2021 - |
Question
Everything works, but this is just to know the correct practice/right approach/what makes sense
Say I have the code:
string query = "SELECT * FROM table WHERE parent_id=@parentId and id = @id";
OleDbCommand c = new OleDbCommand(query, _con);
And for the rest of the part, which of the following is correct? :
c.Parameters.AddWithValue("@parentId", 1);
c.Parameters.AddWithValue("@id", 2);
or
c.Parameters.AddWithValue("parentId", 1);
c.Parameters.AddWithValue("id", 2);
or
c.Parameters.AddWithValue(@"parentId", 1);
c.Parameters.AddWithValue(@"id", 2);
(I know its not the third) Second looks to me the right way. All that depends on how actually a parameterized parameter would be interpreted from the code by SQL. Any thoughts? I am particularly asking because I do not like a more knowledgeable person laughing at my poor habits in coding if ever there can be one here :)
Update: As I come to know, even msdn doesn't follow a convention here, both 1st and 2nd are used. I am going to stick with the 1st which makes it explicit. Thanks
Solution
All will work. Second and third are identical as long as the parameters have sane names (the @
here affects the c# compiler behaviour only), but arguably the second / third are preferable because they work on any connection - including those where @
is not the parameter symbol. However, since the @
is also in the query, that is arguably a weak difference.