I have a c# app that I am working on and wish to run a query and then run another query within the output of the ExecuteReader. My question is that can this be done within a single connection or do I have to close and re-open the connection everytime I want to run a new query?
views:
143answers:
5You can reuse the connection. You may have to change the CommandType, but you don't need to close and reopen the connection. That adds unnecessary overhead.
You can do it with a single connection.
You don't need to open and then close, and the prefered method in this case is to keep the connection open.
You do not have to close it.
using(connection...) { query1; query2; }
Regards.
You can run one query after the other using the same connection. However, the DataReader uses the connection to read the result, so you have to read the result and close the reader before you can run the next query.
If you would need to run another query for each row in the result, you would first need to read the result into a collection, so that you can close the reader before looping through the result. Alternatively you could open another connection, but it's better to stick to a single connection if possible.
Also consider if you can get the result in a single query using a join. It's better to run a single query than hundreds.
You may also consider using DataTableReader which is a disconnected reader, you can iterate through it's results without having to store another collection in memory requiring twice the iteration.