4

How do I reuse a SQLCommand for say multiple queries?

e.g

SqlCommand mycommand = new SqlCommand("SElect * from BKLAH", myConnection);
mycommand.ExecuteNonQuery();

Now I want to use mycommand again but use a different SQL query. How would I do this?

2
  • 2
    But I would like to understand why? Commented Dec 24, 2012 at 13:58
  • @dasblinkenlight has given you the answer, however to use it seems somewhat pointless. Commented Dec 24, 2012 at 14:17

2 Answers 2

9

You can set CommandText property of your command, like this:

mycommand.CommandText = @"UPDATE BKLAH SET a = 5 WHERE id=@id";
Sign up to request clarification or add additional context in comments.

Comments

0

I would use it in a USING section.

Command 1:

using (SqlCommand mycommand = new SqlCommand("SElect * from BKLAH", myConnection))
{
mycommand.ExecuteNonQuery();
}

Command 2:

using (SqlCommand mycommand = new SqlCommand("SElect * from BKLAH2", myConnection))
{
mycommand.ExecuteNonQuery();
}

3 Comments

While I completely agree this is what you should do, that's not reusing mycommand.
Exactly. But personally, reusing the same SqlCommand is not a good practice, even it's doable.
Wholehearted agreement, have to be a very specific circumstance, as you effectively you'll be persisting the connection as well, which except for very rare circumstances is a really bad idea in ADO.Net

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.