如何使用Singleton类来获取多个连接?

gst*_*ode 1 java database design-patterns jdbc

我写了一个Singleton类来获取连接.但是,我无法使用Singleton获得连接.

我想使用我的Singleton获取多个连接并使用Singleton连接查询数据库.我总是尝试几种方法,但没有成功.

这是我的Singleton类:

import java.sql.*;

public class ConnectDB {

private static Connection connect;
private static ConnectDB instance;

private ConnectDB()
{

    try {

        Class.forName("com.mysql.jdbc.Driver");
        //connect DB
        connect = DriverManager.getConnection("jdbc:mysql://ip/database","root","password");

    }

    catch(SQLException e)
    {
        System.err.println(e.getMessage());

    }

    catch(ClassNotFoundException e)
    {

        System.err.println(e.getMessage());

    }   
}

  public static ConnectDB getInstance()
  {

      if(instance == null) {

          instance = new ConnectDB();

      }

      return instance;

  }

}
Run Code Online (Sandbox Code Playgroud)

现在,我得到了连接:

 public class NameClass {




public void getInfoDatabase()
{   

       Connection cnn = ConnectDB.getConnection();
       PreparedStatement ps;
       ResultSet rs;

       try {

           ps = cnn.prepareStatement("select *  from tables");

           rs = ps.executeQuery();

           while(rs.next())
           {

               String tables = rs.getString("table1");
               System.out.println(tables);
           }
Run Code Online (Sandbox Code Playgroud)

npi*_*nti 9

如果要有效地使用多个连接,则可能是在连接池之后:

在软件工程中,连接池是维护的数据库连接的缓存,以便在将来对数据库的请求需要时可以重用连接.连接池用于增强在数据库上执行命令的性能.

拥有一个Singleton将返回许多连接的人违背了其目的Singleton,其任务是在调用时提供相同的实例.

我建议你看看这个以前的SO线程,其中各种连接池库进行了讨论.