E. Rowlands E. Rowlands - 1 month ago 7
Java Question

If I pass a JDBC Connection object's value to another Connection object, is only one connection open? (MySQL DB used)

My method returns the value of a

Connection
object.

Public class DatabaseConnection
{
public Connection establishConnection(C)
{
try
{
this.readLogin(); // prompt user to enter String values for user, pass, host
this.createDatabaseIfNeeded(); // make chessleaguedb if not found
conn = DriverManager.getConnection
("jdbc:mysql://"+host+":3306/chessleaguedb", user, pass);
System.out.println("Successfully connected to chessleaguedb");

}
catch (Exception e)
{
// logic
}
return conn; // want the logic to handle opening a connection in this class and method, then pass it to a Connection object in my 'menu' class
}
}


This method is called in another class and passes the return value to a new Connection object that is used from now on.

public class DBAMenu
{
DatabaseConnection startConnection = new DatabaseConnection; // new instance of class that contains the aforementioned method establishConnection()

Connection conn = null;

conn = startConnection.establishConnection();
}


Is there only one database connection being opened here, or two, because I'm returning the value and passing it to a new
Connection
object?

I've tried using the NetBeans debugger, and the
Connection
value remains the same after this process, but admittedly I'm not 100% on the meaning of the value column in Netbeans debugger.

(Not using Java EE so can't use pooling, and can't use open source software to handle pooling as work must be my own for year 2 undergrad project)

Answer

You have used only one connection as you have invoked conn = startConnection.establishConnection(); only once.

You need to implement close the connection, otherwise it will create connection leaks.

You can use like below:

try(Connection conn =startConnection.establishConnection()) {
 //actual logic to perform db operations
} catch(SQLException sqlexe) {
  //log exceptions
}

P.S.: It is not a best practice to handle connections explicitly/manually like this, rather try to implement Connection Pooling.