Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare Connection Variable

Tags:

java

c++

c#

php

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.

like image 582
Amandeep Jiddewar Avatar asked Oct 04 '12 07:10

Amandeep Jiddewar


1 Answers

All three approaches provide different functionality:

  1. Your class owns the connection object and the connection object will stay alive as long as your object stays alive.
  2. The connection object is local to the method and expires once the method returns.
  3. The caller of the method owns the connection object.

The choice depends on:

  • How do you want to handle the ownership of the connection object &
  • You need to bear in mind that the DB connection needs to be open only as long as required and not all the time, while also,
  • How frequently would you want to connect to the database.
like image 63
Alok Save Avatar answered Oct 01 '22 02:10

Alok Save