Search code examples
c#usingsqlconnection

How to pass methods into an open SQL connection


I want to execute methods within a Sql Connection. I want to use the C# "using" object since it makes the connection safe.

The reason I want to execute queries in this way is so I can reuse this connection and build the queries in a separate class/location.

class foo 
{  

 public void connectionMethod()  
    {  
        using(SqlConnection aConnection=new SqlConnection('ConnectionString')  
        {
            //Query here.
        }  
    }  
}  

Thanks for your help!


Solution

  • In the class you where you want to build your queries, declare each method to accept a SqlConnection parameter.

    // query method
    public void SomeQuery(SqlConnection connection)
    {
        ...
    }
    
    
    // use it
    using(SqlConnection aConnection=new SqlConnection('ConnectionString')  
    {
         aConnection.Open();
         otherClass.SomeQuery(aConnection);
    }   
    

    Passing a parameter will create a copy of the reference to the SqlConnection object which will be in scope within the called method. Make sure you don't leak it outside the method though.