我正在浏览一个较旧的应用程序的冗长数据访问代码。每个函数都调用一个存储过程来从Oracle DB中选择一些东西。每个功能或多或少看起来像下面的代码:
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();
}
}
}
我的问题是:
dataReader == null
是否必要? cmd.ExecuteReader()
调用后会不会是NULL?谢谢。
答案 0 :(得分:3)
using statement将简化您的代码。
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
中断堆栈跟踪,并使用结束大括号中的编译器隐式添加finally语句中所需的所有代码。