It sounds like you are trying to "wrap" the function call... So you have a central place to get connection handle, passing in a query and having the reader sent back so you can process it there. As other has commented, the whole closing, getting disposed of, cleanup, etc... What you could do is create an additional parameter to your function that accepts an Action
expecting the data reader. You read what you want and return, then close out what you need to. Below is just a SAMPLE to implement.
Again, not perfect, but principles.. A centralized class will get connection, open, close, release. Prepare the query command you have already established and then passes back and lets the Action method actually handle the reading as different queries will have their own return structure/columns, etc. which is what I THINK you are trying to wrap up.
You would still want your try/catch, such as no valid open/close connection, add your dispose calls, but the principle might be what you are looking for.
public class MyQueryWrapper
{
public GetMyData(OleDbCommand cmd, Action<OleDbDataReader> letYouReadIt)
{
using (var conn = new OleDbConnection(yourConnectionString))
{
conn.Open();
cmd.Connection = conn;
using (var rdr = cmd.ExecuteReader())
{
// Now, call YOUR routine with the reader object while
// it is still active...
letYouReadIt(rdr);
}
conn.Close();
}
}
}
public class YourOtherClass
{
public void GetUser()
{
var mqr = new MyQueryWrapper();
var sqlcmd = new OleDbCommand();
// prepare the command and parameters.
myUsers = new List<someUsers>();
mqr.GetMyData(sqlcmd, ReadRecordsHere);
}
private List<someUsers> myUsers;
public void ReadRecordsHere(OleDbReader rdr)
{
while (rdr.Read())
{
// read record, add to the "myUsers" list
// keep reading until all records, then get out
}
}
}