Error Too many connections

0

I was creating my querys and suddenly

The issue is that I can not continue with the development of my program

I leave the code of my connection

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;

public class Conexion {


Connection cnx;

 public Connection getCnx(){
      try {
            Class.forName("com.mysql.jdbc.Driver");
            cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/myl", "root", "");

          }catch (ClassNotFoundException | SQLException ex) {
           JOptionPane.showMessageDialog(null,"Error de Acceso:\n No hay conexion a la base de datos\n:"+ ex,"Error", JOptionPane.ERROR_MESSAGE);

      }

           return cnx;
           }

public void closeCnx() throws SQLException{

      if(cnx != null){

              cnx.close();

    }
}

}

and this is the code of my query

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;

public class Querys {


Conexion CNX=new Conexion();
PreparedStatement SQL;
List validation = new ArrayList();
Connection con = CNX.getCnx();
Object[] titulos = {"id","nombre","tipo","fecha","hora"};
DefaultTableModel dtm = new DefaultTableModel(null,titulos);

  public List LogIn(String user) throws SQLException, IOException, ClassNotFoundException {
    String queryPassword = "SELECT users, pass FROM log WHERE users='"+user+"'";
    SQL = con.prepareStatement(queryPassword);
    ResultSet result = SQL.executeQuery();
    String PassDB = null;
    String UserDB = null;
   if (result.next()){
          UserDB=result.getString("users");
          PassDB=result.getString("pass");
          validation.add(UserDB);
          validation.add(PassDB);

   }
   CNX.closeCnx();
    return validation;
  }

  public DefaultTableModel buscarTorneo(String fecha) throws SQLException, IOException, ClassNotFoundException {

      String queryPassword = "SELECT * FROM 'torneo' WHERE fecha='"+fecha+"'";
    SQL = con.prepareStatement(queryPassword);
    ResultSet result = SQL.executeQuery();
   if (result.next()){

          dtm.addRow(new Object[]{
            result.getString("id"),
            result.getString("nombre"),
            result.getString("tipo"),
            result.getString("fecha"),
            result.getString("hora")
   });
   }
    CNX.closeCnx();
    return dtm;
    }

        public void crearTorneo(String nombre,String tipo, String fecha,String h) throws SQLException, IOException, ClassNotFoundException{
     String query = "INSERT INTO torneo (nombre, tipo, fecha, hora) "
                + "VALUES ('"+nombre+"','"+tipo+"','"+fecha+"','"+h+"');";
     SQL = con.prepareStatement(query);
    SQL.execute();
    CNX.closeCnx();
      }

}

I hope you can help me as I searched everywhere but I can not find concise information about it.

Geacias

    
asked by Sodro 14.01.2018 в 18:27
source

2 answers

0

Well, your code has several problems as you have structured one of them most serious and that makes you the error of the connections is a PreparedStatement global that you use in all methods and never close. Never ! put a PreparedStatement or a ResultSet global again. It is not necessary because after finishing using them in a method you must close them.

To close the connections you must do it unlike how they were opened when you are going to make a query you do it opening the connection first, then the PreparedStatement and finally the Resulset in case you need to see this the second resultSet must be closed first the PreparedStatamente and third the Connection.

The other problem that you have in your code is that you are always thinking that everything is going to flow normally and although that is due it does not always happen, I tell you this because you close the connections after executing the SQL statement but that happens if an error occurs when executing it or an error before it can be executed? The answer is you would have the connection open because you never reached the line that closes.

For this reason Always ! close your connection in a block finally always asking if it is null so you do not generate more errors.

I leave your code with the changes explained in the answer:

Postadata : In the java documentation it says that if you close the statement the resultSet is closed and so on but I've had several chest beats for ignoring that.

Last but not the least is that whenever you create an instance of Query Query query = new Query(); you are creating a connection to the database in the Connection con = CNX.getCnx(); statement which is tricky because if you do not perform any action the connection is never will close.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;

public class Conexion {

    public Connection getCnx() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/myl", "root", "");
        } catch (ClassNotFoundException | SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error de Acceso:\n No hay conexion a la base de datos\n:" + ex, "Error", JOptionPane.ERROR_MESSAGE);
        }
        return null;
    }

    public void closeCnx(Connection cnx) throws SQLException {
        if (cnx != null) {
            cnx.close();
        }
    }
}

And the Query class

    import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;

public class Querys {

    Conexion CNX = new Conexion();


    Object[] titulos = {"id", "nombre", "tipo", "fecha", "hora"};
    DefaultTableModel dtm = new DefaultTableModel(null, titulos);

    public List LogIn(String user) throws SQLException, IOException, ClassNotFoundException {

        Connection con = CNX.getCnx();

        List validation = new ArrayList();
        PreparedStatement sql = null;
        ResultSet result = null;
        try {
            String queryPassword = "SELECT users, pass FROM log WHERE users='" + user + "'";
            sql = con.prepareStatement(queryPassword);
            result = sql.executeQuery();
            String PassDB = null;
            String UserDB = null;
            if (result.next()) {
                UserDB = result.getString("users");
                PassDB = result.getString("pass");
                validation.add(UserDB);
                validation.add(PassDB);

            }
        } finally {
            if (result != null) {
                result.close();
            }

            if (sql != null) {
                sql.close();
            }

            CNX.closeCnx(con);
        }
        return validation;
    }

    public DefaultTableModel buscarTorneo(String fecha) throws SQLException, IOException, ClassNotFoundException {

        Connection con = CNX.getCnx();

        PreparedStatement sql = null;
        ResultSet result = null;

        try {
            String queryPassword = "SELECT * FROM 'torneo' WHERE fecha='" + fecha + "'";
            sql = con.prepareStatement(queryPassword);
            result = sql.executeQuery();
            if (result.next()) {

                dtm.addRow(new Object[]{
                    result.getString("id"),
                    result.getString("nombre"),
                    result.getString("tipo"),
                    result.getString("fecha"),
                    result.getString("hora")
                });
            }
        } finally {
            if (result != null) {
                result.close();
            }

            if (sql != null) {
                sql.close();
            }

            CNX.closeCnx(con);
        }
        return dtm;
    }

    public void crearTorneo(String nombre, String tipo, String fecha, String h) throws SQLException, IOException, ClassNotFoundException {
        String query = "INSERT INTO torneo (nombre, tipo, fecha, hora) "
                + "VALUES ('" + nombre + "','" + tipo + "','" + fecha + "','" + h + "');";

        Connection con = CNX.getCnx();

        PreparedStatement sql = null;

        try {
            sql = con.prepareStatement(query);
            sql.execute();
        } finally {
            if (sql != null) {
                sql.close();
            }

            CNX.closeCnx(con);
        }
    }
}
    
answered by 14.01.2018 / 18:58
source
0

Generally this indicates that the connections are not being closed correctly, make sure that the cnx.close(); is executed and that the exception is not being skipped directly.

For a temporary solution, increase the limit of connections to the database and restart the MySQL so that the sessions are closed.

    
answered by 14.01.2018 в 19:03