小编gst*_*ode的帖子

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

我写了一个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 …
Run Code Online (Sandbox Code Playgroud)

java database design-patterns jdbc

1
推荐指数
1
解决办法
9300
查看次数

标签 统计

database ×1

design-patterns ×1

java ×1

jdbc ×1