Reusing parameters

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

Miha Markic [MVP C#]

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

Sheila Jones

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top