Reputation: 50
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!
Upvotes: 0
Views: 932
Reputation: 43023
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.
Upvotes: 1