Reusing parameters

  • Thread starter Thread starter Sheila Jones
  • Start date Start date
S

Sheila Jones

Hello,

I have created an OleDbCommand as follows:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM PRODUCTS WHERE ID=?",
con);
cmd.Parameters.Add("@id", OleDbType.Char);
cmd.Parameters["@id"].Value="CDTR";
I then use a DataReader to read the result, process it and close the reader.

Then I change the command text:
cmd.CommandText="SELECT * FROM ORDERS WHERE ID=?";

The @id parameter still exists from the previous version and is the correct
type, so I am reusing it:
cmd.Parameters["@id"].Value="CHBRWN";

Then I use another ExecuteReader call to fetch the result. It seems to work
OK, but my question is: Is it OK to reuse the parameter like this, or should
I delete and recreate it? Or should I be using two separate command objects?

Thanks.
 
Hi Sheila,

Yes, it works and there is no penalty AFAIK.
However I've read a recommendation that you should use different command
instances for different sql stataments.
 
Thank you for the reply. I must admit I was a bit surprised the parameter
was still there after I'd changed the command text - I thought any
parameters would have been invalidated and the Parameters collection
cleared.

It probably is better to use two separate commands though, if only to help
code readability.


Miha Markic said:
Hi Sheila,

Yes, it works and there is no penalty AFAIK.
However I've read a recommendation that you should use different command
instances for different sql stataments.

--
Miha Markic [MVP C#] - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com

Sheila Jones said:
Hello,

I have created an OleDbCommand as follows:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM PRODUCTS WHERE ID=?",
con);
cmd.Parameters.Add("@id", OleDbType.Char);
cmd.Parameters["@id"].Value="CDTR";
I then use a DataReader to read the result, process it and close the reader.

Then I change the command text:
cmd.CommandText="SELECT * FROM ORDERS WHERE ID=?";

The @id parameter still exists from the previous version and is the correct
type, so I am reusing it:
cmd.Parameters["@id"].Value="CHBRWN";

Then I use another ExecuteReader call to fetch the result. It seems to work
OK, but my question is: Is it OK to reuse the parameter like this, or should
I delete and recreate it? Or should I be using two separate command objects?

Thanks.
 
Back
Top