If methods/functions I'm going to call involve the need of an open SqlConnection, I will open this up in the method which is calling the function. For example:
protected static void btnSubmit(){
conn.Open();
myMethod(someParam, conn);
conn.Close();
}
protected static void myMethod(object someParam, SqlConnection conn){
//Some SQL commands etc here..
}
I do this so that I:
- Only ever open and close 1 SqlConnection per process
However, would it be better to structure my code like so:
protected static void btnSubmit(){
myMethod(someParam);
}
protected static void myMethod(object someParam){
SqlConnection conn = New SqlConnection(".....");
conn.Open();
//Some SQL commands etc here..
conn.Close();
}
The advantage I see of structuring it this way is:
- I don't have to pass an extra parameter for each method
- If later down the line the method no longer has a SQL command, there is not an unused parameter being called each time
The disadvantage I see to this, is:
- If
myMethod
is a recursive method, then when it calls itself its going to be opening anotherSqlConnection
, and so on, and so on.. - If
btnSubmit
is calling multiple methods which all require a SqlConnection, each one is going to open and close a new connection.
What is the best way of doing this, and which is most commonly practised?