Using one sqlconnection/sqlcommand through 2 DB-bound methods

Posted by dotnetdev on Stack Overflow See other posts from Stack Overflow or by dotnetdev
Published on 2009-06-16T22:20:09Z Indexed on 2010/03/23 9:03 UTC
Read the original article Hit count: 339

Filed under:

I have a class with a method which gets data from a database through a SELECT stored proc. This method uses a SqlDbReader by returning ExecuteReader() on a SqlCommand.

The connection and everything is made in this method, with fields (such as connection string) set as class level fields.

I now need to populate an array based on the results of this query (so the columns of each row will go into the array with its own index).

However, this query will not select all of the data from one table which is involved. I can write the queries to get what I need, but how can I use one connection throughout the class? If I instantiate the connection object and call Open() in the constructor, I get an exception @ runtime.

I'm hoping for something like this:

// At class level: sqlconn.Open(); // sqlcommand set up

Method() { // Fire stored proc // Insert results in a collection }

Method2() { // Pass same collection in (use same one), // Add new row columns into same collection }

How can I do this with strict performance in mind?

Thanks

© Stack Overflow or respective owner

Related posts about c#