我有以下两组代码。我的问题是我们需要为命令和适配器使用“using”吗,还是只需为连接使用?正确的做法是什么?
using (OracleConnection conn = new OracleConnection(ConnectionString))
{
conn.Open();
OracleCommand command = new OracleCommand(ProcedureName)
{
CommandType = CommandType.StoredProcedure,
Connection = conn
};
command.Parameters.Add(new OracleParameter("P_ID", OracleDbType.Varchar2, Id, ParameterDirection.Input));
command.Parameters.Add(new OracleParameter("CUR_OUT", OracleDbType.RefCursor, ParameterDirection.Output));
OracleDataAdapter adapter = new OracleDataAdapter(command);
adapter.Fill(dt);
}
上面的代码只有一个using语句,而下面的代码有三个using语句。
using (OracleConnection conn = new OracleConnection(ConnectionString))
{
await conn.OpenAsync();
using (OracleCommand oCommand = new OracleCommand(ProcedureName))
{
oCommand.BindByName = true;
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.CommandTimeout = await GetCommandTimeout(DatabaseConstants.OracleCommandTimeoutInSeconds);
oCommand.Connection = conn;
oCommand.Parameters.Add(new OracleParameter("P_ID", OracleDbType.Varchar2, Id, ParameterDirection.Input));
oCommand.Parameters.Add(new OracleParameter("CUR_OUT", OracleDbType.RefCursor, ParameterDirection.Output));
using (OracleDataAdapter oDatAdapter = new OracleDataAdapter(oCommand))
{
oDatAdapter.Fill(dataSet);
}
}
}