I'm going over a lengthy data access code of a somewhat older app. Every function is calling a stored procedure to select something from Oracle DB. Every function more or less looks like the code below:
public List<SomeObject> GetMeSomethingFromDB(string myParam, int anotherParam)
{
OracleConnection conn = null;
OracleDataReader dataReader = null;
try
{
conn = new OracleConnection(Settings.ConnectionString);
conn.Open();
var cmd = new OracleCommand("STORED_PROC_NAME", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("IN_MY_PARAM", OracleDbType.Varchar2)).Value = myParam;
cmd.Parameters.Add(new OracleParameter("IN_ANOTHER_PARAM", OracleDbType.Int32)).Value = anotherParam;
cmd.Parameters.Add(new OracleParameter("OUT_REF_CURSOR", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
dataReader = cmd.ExecuteReader();
List<SomeObject> result = new List<SomeObject>();
if (dataReader == null || !dataReader.HasRows) return result;
while (dataReader.Read())
{
SomeObject someObject = new SomeObject
{
SomeId = (int)dataReader["SOME_ID"],
SomeStringValue = dataReader["SOME_STRING_VALUE"].ToString()
};
result.Add(someObject);
}
return result;
}
catch (Exception e)
{
throw e;
}
finally
{
if (dataReader != null)
{
dataReader.Close();
dataReader.Dispose();
}
if (conn != null)
{
if (conn.State == ConnectionState.Open) conn.Close();
conn.Dispose();
}
}
}
My questions are:
dataReader == null
necessary? Would it ever be NULL after cmd.ExecuteReader()
call?The using statement will simplify a lot your code.
public List<SomeObject> GetMeSomethingFromDB(string myParam, int anotherParam)
{
using (OracleConnection conn = new OracleConnection(Settings.ConnectionString))
using (OracleCommand cmd = new OracleCommand("STORED_PROC_NAME", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("IN_MY_PARAM", OracleDbType.Varchar2)).Value = myParam;
cmd.Parameters.Add(new OracleParameter("IN_ANOTHER_PARAM", OracleDbType.Int32)).Value = anotherParam;
cmd.Parameters.Add(new OracleParameter("OUT_REF_CURSOR", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
using (OracleDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
SomeObject someObject = new SomeObject
{
SomeId = (int)dataReader["SOME_ID"],
SomeStringValue = dataReader["SOME_STRING_VALUE"].ToString()
};
result.Add(someObject);
}
}
}
return result;
}
throw e
and all the code required in the finally statement is implicitly added by the compiler in the using closing curly brace.