太多客户端任务异常

太多客户端任务异常

我正在通过JAVA程序创建JDBC ODBC连接。我必须多次进行这种连接。一段时间后,程序将引发“太多客户端任务异常”。如何才能解决这个问题。我正在粘贴我的要求的示例示例

class connectiondemo
{

public void connect()
{

 try {

   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection con=DriverManager.getConnection("Jdbc:Odbc:dsn");
   Statement st= con.createStatement();

   }

  catch(Exception ex)
  {
   ex.printStackTrace();
  }
 }
}


calling programs

 class
 {
  public static void main(String args[])

   {
    //supose i have to call connect methods thousands of times then what is the solution

    connectdemo demo= new connectdemo();
   dem0.connect();

   }
  }

最佳答案

关键是保存连接。为什么不使用静态方法来调用连接,如下所示:

public class Connector {

private static final String URL = "jdbc:mysql://localhost/";
private static final String LOGIN = "root";
private static final String PASSWORD = "azerty";
private static final String DBNAME = "videotheque";
private static Connector connector;
private static Connection connection;

private Connector() {
}

public synchronized static Connector getInstance() {
    if (connector == null) {
        connector = new Connector();
    }
    return connector;
}

public static Connection getConnection() {
    if (connection == null) {
        Connection c = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            c = DriverManager.getConnection(URL + DBNAME, LOGIN, PASSWORD);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return c;
    }
    return connection;
}


对于连接,您可以将其用作:

Connector.getInstance().getConnection()

07-23 12:06