如何在整个应用程序中使用一个数据库连接对象?

Dhr*_*tel 10 java mysql odbc jdbc java-ee

我创建了这个返回连接对象的类.我用过MySQL数据库.

public class Connect_db {        
    public Connection getConnection(String db_name,String user_name,String password)
    {
        Connection con=null;
        try
        {
        Class.forName("com.mysql.jdbc.Driver");
        con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return con;        
    }
}  
Run Code Online (Sandbox Code Playgroud)

现在我想做的就是实例化这个类一次并得到连接对象.我想在整个应用程序中使用同一个对象.另一个解决方案也将受到赞赏.

Iły*_*sov 10

我想你需要单例模式,这里有一个简单的例子:

public class Connect_db {        
    static Connection con=null;
    public static Connection getConnection()
    {
        if (con != null) return con;
        // get db, user, pass from settings file
        return getConnection(db, user, pass);
    }

    private static Connection getConnection(String db_name,String user_name,String password)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return con;        
    }
} 
Run Code Online (Sandbox Code Playgroud)

那么你将能够使用这样的连接:

Connect_db.getConnection().somemethods();
Run Code Online (Sandbox Code Playgroud)

但是,您应该考虑 - 当多个线程尝试向数据库发出请求时,这将在多线程环境中如何工作.