如何访问从java中的类返回的连接引用对象?

时间:2016-08-19 10:39:28

标签: java mysql eclipse jdbc

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;
    }


}

这是属于单独包的类。我想在另一个类中访问此返回的连接对象。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

创建一个DBUtil对象,然后在连接变量上调用getDBConnection(),如下所示:

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

答案 1 :(得分:0)

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();
    }
}

}