using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT * FROM Products"; command.CommandType = CommandType.Text; var reader = command.ExecuteReader(); while (reader.Read()) { // Read data } // Call Dispose to release resources command.Dispose(); } // Call Dispose to release resources connection.Dispose(); }
var factory = DbProviderFactories.GetFactory(providerName); using (var connection = factory.CreateConnection()) { connection.ConnectionString = connectionString; connection.Open(); using (var command = factory.CreateCommand()) { command.Connection = connection; command.CommandText = "SELECT * FROM Products"; command.CommandType = CommandType.Text; var reader = command.ExecuteReader(); while (reader.Read()) { // Read data } // Call Dispose to release resources command.Dispose(); } // Call Dispose to release resources connection.Dispose(); }In this example, the DbCommand object is created using the CreateCommand() method of a DbProviderFactory object retrieved from the DbProviderFactories class. The DbCommand object is disposed of using the Dispose() method. The package library used in this example would depend on the specific providerName specified when retrieving the DbProviderFactory object.