【问题标题】:How to access connection reference object that is returned from a class in java?如何访问从java中的类返回的连接引用对象?
【发布时间】:2016-08-19 10:39:27
【问题描述】:
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;
    }


}

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

【问题讨论】:

    标签: java mysql eclipse jdbc


    【解决方案1】:

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

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

    【讨论】:

    • thanks....public static Connection getDBConnection()...... if static 如何访问它..???
    • 如果它是静态的,那么你不需要实例化一个对象来调用它。你可以直接调用它。
    【解决方案2】:
    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();
        }
    }
    

    }

    【讨论】:

    • 此代码可能对您有所帮助。 thic 类有两种方法创建了一个单例类已经使用过。当你想要访问数据库连接时,你可以使用下面的代码 DBClass db=DBClass.getInstace();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 2018-08-26
    相关资源
    最近更新 更多