Tengo mi clase MySQLConnection donde hago mi conexión con el driver, etc. En la clase TrailerBox llamo el método estático para obtener conexión y lo utilizo para realizar una consulta. Se supone que funciona "correctamente", pero cuando intento realizar mas de 151 constructores de mi clase (consultas a la db), me aparece el siguiente error:
Data source rejected establishment of connection, message from server: "Too many connections"
Estas son mis clases: MySQLConnection.java
package models;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
//mysql parameters
private static final String SERVER = "localhost";
private static final String DATABASE = "logistics";
private static final String USER = "root";
private static final String PASSWORD = "";
//get connection
public static Connection getConnection() {
//connection
Connection connection = null;
try {
//connection string
String connectionString = "jdbc:mysql://" + SERVER + "/" + DATABASE + "?user=" + USER + "&serverTimezone=UTC";
//add password to connection string if needed
if (PASSWORD != "") {
connectionString += "&password=" + PASSWORD;
}
//MySQL Java Drivers
//Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Class.forName("com.mysql.jdbc.Driver").newInstance();
//MySQL connection
connection = DriverManager.getConnection(connectionString);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
System.out.println(ex.getMessage());
}
return connection;
}
}
Y este es el constructor donde utilizo el metodo:
public static ArrayList<TrailerBox> getAll() {
ArrayList<TrailerBox> list = new ArrayList<>();
PreparedStatement command;
ResultSet result;
String query = "select s.id, s.description, s.ipAddress from trailerboxes as s order by s.id";
try {
//prepare statement
command = MySQLConnection.getConnection().prepareStatement(query);
//execute query
result = command.executeQuery();
//read rows
while (result.next()) {
//read fields
int id = result.getInt("id");
String description = result.getString("description");
String ipAddress = result.getString("ipAddress");
//add new order to list
list.add(new TrailerBox(id, description, ipAddress));
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
//return list
return list;
}
Intente agregando un finally
a mi try-catch de la conexión:
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
Pero me arroja este mensaje:
No operations allowed after connection closed.
De antemano, les agradezco su ayuda, saludos!