Thursday, December 20, 2007

"Using" keyword in Data Access Base classes..

Introduction

this example demonstrates use of "Using" keyword which disposes all resources used inside it and
in Data Access base classes we don't have to worried about connection and adapter ispose, they will
be disposed automatically immediatly after use..

internal DataTable GetNetworkSettingsByNetworkID(int networkID)
{
try
{
using (Connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
command.CommandText = SQL_GET_NETWORKSETTINGS_BY_NETWORKID;
command.CommandType = CommandType.StoredProcedure;
command.Connection = Connection;
command.Parameters.Add(new MySqlParameter("?_NetworkID", MySqlDbType.Int32));
command.Parameters[0].Value = networkID;
using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command))
{
using (DataTable dtNetworkSettings = new DataTable())
{
dataAdapter.Fill(dtNetworkSettings);
return dtNetworkSettings;
}
}
}
}
}
catch (Exception ex)
{
PacketUtils.WriteLogError(ex, "NetworkDA::GetNetworkSettingsByNetworkID");
throw ex;
}
finally
{
if (Connection != null)
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
Connection.Dispose();
}
}
}

No comments: