0

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

ಠ_ಠ
  • 3,060
  • 28
  • 43
nawfal
  • 70,104
  • 56
  • 326
  • 368
  • Have you read [the documentation](http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbparameter.aspx)? – Tim Schmelter May 06 '12 at 20:50
  • @TimSchmelter nope, but my question is not related to microsoft products alone, just any db – nawfal May 06 '12 at 20:51
  • 1
    Just a note: your example is using OleDb, and OleDb is...different. It doesn't complain about named parameters, but it doesn't use them. The parameter names get translated into "?" and the values get supplied in index order as they appear in the sql text. – LarsTech Sep 23 '20 at 21:59

1 Answers1

5

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900