I thought it would be nice to setup a database "accessor" (DBA) class where you could instantiate it, provide a connection string and use it's methods to do all of the database tricks. This is a sample of what I have. I'll describe the problem below...
This is a method that returns a datareader it's part of the DBA class.
This is a call to the method from another class.
Pretty simple right? Well as you may have noticed; if I close the connection in the GetOraDataReader method I can no longer use the DataReader in the class that instantiated the DBA. I have to be able to close the connection to the database when the method is done.
So my question: is there a way to pass the DataReader (in this case) back to the calling the calling method and still be able to close the connection?
Am I stuck just putting database activities in the class, doesn’t this go against the “black box” practice in OOP?
I am still learning about OOP and C# maybe it's not meant to be done this way.
Thanks for your thoughts
This is a method that returns a datareader it's part of the DBA class.
Code:
.... omitted code ...
public OracleDataReader GetOraDataReader(string sqlStr)
{
OraConn = new OracleConnection();
OraConn.ConnectionString=m_connStr;
try
{
OraConn.Open();
OraCmd = new OracleCommand(sqlStr,OraConn);
return OraCmd.ExecuteReader();
}
catch(OracleException ex){
throw(ex);
}
finally
{
OraConn.Close();
}
}
....
This is a call to the method from another class.
Code:
...
OracleDataReader reader = m_dba.GetOraDataReader("SELECT PASSWORDHASH, SALT FROM WEBCZCS.CZCS_USERS WHERE USER_NAME='" + m_userName + "'");
string dbPasswordHash="";
string salt="";
// for lack of a better way to check for the existance of records in an Oracle reader.
bool hasRecords = false;
while(reader.Read()){
dbPasswordHash = reader.GetString(0);
salt = reader.GetString(1);
hasRecords=true;
}
if(!hasRecords) return false;
...
Pretty simple right? Well as you may have noticed; if I close the connection in the GetOraDataReader method I can no longer use the DataReader in the class that instantiated the DBA. I have to be able to close the connection to the database when the method is done.
So my question: is there a way to pass the DataReader (in this case) back to the calling the calling method and still be able to close the connection?
Am I stuck just putting database activities in the class, doesn’t this go against the “black box” practice in OOP?
I am still learning about OOP and C# maybe it's not meant to be done this way.
Thanks for your thoughts