sathiya
sathiya

Reputation: 3

How to access connection reference object that is returned from a class in java?

package com.wipro.book.util;
import java.sql.*;

public class DBUtil {

    public Connection getDBConnection() throws Exception
    {
        Connection con = null;
        String url = "jdbc:mysql://localhost:3306/library";
        String driver = "com.mysql.jdbc.Driver";
        String username = "root";
        String password = "";

        try
        {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
            System.out.println("connection success");
            return con;
        }
        catch(ClassNotFoundException e){
            System.out.println("something wrong"+e);
        }
        return null;
    }


}

This is the class belonging to a separate package. I want to access this returned connection object in another class. How can I achieve this?

Upvotes: 0

Views: 408

Answers (2)

Gherbi Hicham
Gherbi Hicham

Reputation: 2584

Create a DBUtil object and then call the getDBConnection() on a connection variable like this:

    DBUtil dbutilObject= new DBUtil ();
    //YOUR CONNECTION VARIABLE
    Connection con1 = dbutilObject.getDBConnection();

Upvotes: 1

venkey
venkey

Reputation: 82

public class DBClass {
private  Connection con;
final   String driverClass = "com.mysql.jdbc.Driver";
final  String url = "jdbc:mysql://localhost:3306/xxxx";      
final  String username = "root";
final  String password = "";        
private static class db_helper
{
    private static final DBClass INSTANCE = new DBClass();
}
public static DBClass getInstance(){

    return db_helper.INSTANCE;
}


public  void makeCon() {
    try {
        Class.forName(driverClass);

        con = DriverManager.getConnection(url, username, password);
        System.out.println("connection established");
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

public   Connection getCon() throws SQLException {
    if(con==null)
    {
        con = DriverManager.getConnection(url, username, password);
    }
    return con;
}

public void closeCon() {
    try {
        con.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

}

Upvotes: 0

Related Questions