以下のような仕組みが必要な場合はありますか?
using (Something something = new Something())
{
try
{
}
finally
{
something.SomeCleanup();
}
}
または、すべてのクリーンアップタスクを暗黙のsomething.Dispose()
呼び出しで実行する必要がありますか?
問題のあるコードは次のとおりです。
public static DataTable GetDataTable(string cmdText, IEnumerable<Parameter> parameters)
{
// Create an empty memory table.
DataTable dataTable = new DataTable();
// Open a connection to the database.
using (SqlConnection connection = new SqlConnection(ConfigurationTool.ConnectionString))
{
connection.Open();
// Specify the stored procedure call and its parameters.
using (SqlCommand command = new SqlCommand(cmdText, connection))
{
command.CommandType = CommandType.StoredProcedure;
SqlParameterCollection parameterCollection = command.Parameters;
foreach (Parameter parameter in parameters)
parameterCollection.Add(parameter.SqlParameter);
try
{
// Execute the stored procedure and retrieve the results in the table.
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
try
{
dataAdapter.Fill(dataTable);
}
catch
{
dataTable.Dispose();
dataTable = null;
}
}
finally
{
//parameterCollection.Clear();
}
}
}
return dataTable;
}
注:この関数のユーザーがsの作成を直接Parameter
処理する必要がないように、クラスを定義しました。SqlParameter
クラスのSqlParameter
プロパティをParameter
使用して、を取得できますSqlParameter
。
ある時点で、私のプログラムは次のことを行います(多くのクラスが含まれるため、コードを投稿できません。基本的に、多くのオブジェクトを作成するミニフレームワークがあります)。
- の配列を作成します
Parameter
。 GetDataTable('sp_one', parameters)
。GetDataTable('sp_two', parameters)
。