Search code examples
c#dbconnectiondbproviderfactories

Using DbConnection without opening it first


I am accessing a DB using the generic DbConnection provided by DbProviderFactories and I have observed that I don´t need to call Open before using the connection. I provide a sample code that is working (either using "System.Data.SqlClient" or "Oracle.DataAccess.Client" as the providerInvariantName parameter). I have performed all CRUD operations with similar code without explicitly calling Open on the connection, without any noticeable error.

I understand that I don´t need to close it, since the using statement takes care of closing and disposing the connection. But, when is the connection opened in this code, then? Is it automatically opened when I call Fill on the associated DataAdapter? Is there any consequence of not explicitly calling Open on the connection object before using it? Because if it is unnecesary and I can save myself a couple of lines of code I will sure do. ;-)

DbProviderFactory myFactoryProvider = DbProviderFactories.GetFactory("System.Data.SqlClient");// same with "Oracle.DataAccess.Client"
using (var myConnection = myFactoryProvider.CreateConnection())
using (var myCommand = myFactoryProvider.CreateCommand())
{
    try
    {       
        // Set up the connection                  
        myConnection.ConnectionString = _someConnectionString;
        myCommand.Connection = myConnection;
        myCommand.CommandText = "SELECT * FROM SOME_TABLE";     

        // Create DataAdapter and fill DataTable                    
        DbDataAdapter dataAdapter = myFactoryProvider.CreateDataAdapter();
        dataAdapter.SelectCommand = myCommand;
        DataTable myTable = new DataTable();
        dataAdapter.Fill(myTable);
        // Read the table and do something with the data
        foreach (DataRow fila in myTable.Rows)
        {
            // Do  something
        }                          
    }
    catch (Exception e)
    {
        string message = e.ToString();
        throw;
    }
} //using closes and disposes the connection and the command

Solution

  • The connection to the db should be established and opened when the statement

    dataAdapter.Fill(myTable);
    

    runs, so your code goes well as is