I want to know which is safe & better way to use Connection variable of following.
First : Connection as class member variable of class
class MyClass
{
Connection conn;
public MyClass(Connection conn) {
this.conn = conn;
}
public void myMethod(){
//Do some DB operations using conn
}
}
Second : Initialize connection in method
class MyClass
{
public MyClass() {
}
public void myMethod(){
Connection conn= initializeFunction(); //Initialize Connection
//Do some DB operations using conn
}
}
Third : Send connection as argument to function
class MyClass
{
public MyClass() {
}
public void myMethod(Connection conn){
//Do some DB operations using conn
}
}
NOTE : Question is not programming language specific, hence I have added tags other than Java as well.
When it comes to Database Connection object, the best is: To open as late as possible and close as early as possible.
In C# there is a
usingstatement which works with objects implementing IDisposable interface.usingstatement works like try/finally block of code. IMO the general practice for handling connection should be something like:For your options, I believe the first one is the worst, which holds the connetion object along with the object of the class.
I think you should be more concerned about opening/closing the connection rather than holding the object of the connection in multiple places.