I am developing my first application as a univ project. using MySQL with JAVA, I am realizing that there are methods and routines that do not close the connections and the statements although I give them their respective orders to do it, something I must do in a correct way so that this does not happen, that they suggest ?
WARNING: THIS CODE THAT IS SHOWN HERE CONTAINS ERRORS OF INSTRUCTIONS, YOU CAN TAKE IT AS AN EXAMPLE TO KNOW HOW TO CREATE A LOGIN AND HOW TO MAKE DIFFERENT OPERATIONS WITH A TABLE OF USERS BUT THE GENERA CONNECTION CLASS CONNECTIONS OF MORE AND DO NOT CLOSE READ WELL THE FULL POST NOT TO FALL IN THE SAME ERROR THAT I DO.
This is the class I use to connect.
package metodos;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Conexion {
private static final String DB = "sil";
private static final String DBuser = "root";
private static final String DBpwd = "****";
private static final String DBurl = "jdbc:mysql://localhost:3306/" + DB;
Connection Conector;
public Conexion() {
try {
Class.forName("com.mysql.jdbc.Driver");
Conector = DriverManager.getConnection(DBurl, DBuser, DBpwd);
} catch (ClassNotFoundException classNotFoundException) {
JOptionPane.showMessageDialog(null, "Error con el driver JDBC");
} catch (SQLException exception) {
try {
JOptionPane.showMessageDialog(null, "Error en la conexion");
Conector.close();
} catch (SQLException ex) {
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public Connection getConexion() {
return Conector;
}
/**
* ¿ES NECESARIO ESTE METODO?
* Este metodo cierra la conexion, para su uso
* el manejo de recursos del sistema.
*/
/*public void cierraConexion() {
try {
Conector.close();
} catch (Exception exception) {
// TODO: handle exception
System.out.println("Error cerrando la conexion");
}
}//Cierre del constructor*/
}//Fin de la clase Conexion
And this class uses the connection and generates connections in excess.
package metodos;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class OperacionesUsuarios {
Conexion Conecta = new Conexion();
Connection Conector;
public Object[][] AccedeUsuario(String login, String clave) {
Conector = Conecta.getConexion();
int registros = 0;
int usu_id;
try {
String Query = "SELECT count(1) as cont" + " FROM usuarios";
Statement St = Conector.createStatement();
/*
PreparedStatement pstm = Conn.prepareStatement(Query);
ResultSet Rs = pstm.executeQuery();
*/
try (ResultSet Rs = St.executeQuery(Query)) {
/*
PreparedStatement pstm = Conn.prepareStatement(Query);
ResultSet Rs = pstm.executeQuery();
*/
Rs.next();
registros = Rs.getInt("cont");
Rs.close();
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error en la consulta MySQL");
Logger.getLogger(OperacionesLicorerias.class.getName()).log(Level.SEVERE, null, sqle);
}
Object[][] data = new Object[registros][3];
if (login.length() != 0 && clave.length() != 0) {
String usu_login;
String usu_password;
try {
String Query = "SELECT * FROM sil.usuarios WHERE login = '"
+ login + "' AND clave = '" + clave + "'";
Statement St = Conector.createStatement();
/* PreparedStatement pstm = Conn.prepareStatement(Query);
try (ResultSet Rs = pstm.executeQuery()) {
*/
try (ResultSet Rs = St.executeQuery(Query)) {
int i = 0;
while (Rs.next()) {
usu_id = Rs.getInt("idUsuarios");
usu_login = Rs.getString("login");
usu_password = Rs.getString("clave");
data[i][0] = usu_id;
data[i][1] = usu_login;
data[i][2] = usu_password;
i++;
}
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error en la consulta MySQL");
Logger.getLogger(OperacionesLicorerias.class.getName()).log(Level.SEVERE, null, sqle);
} finally {
try {
if (Conector != null) {
Conector.close();
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error al cerrar la conexion");
Logger.getLogger(OperacionesLicorerias.class.getName()).log(Level.SEVERE, null, sqle);
}
}
}
return data;
}
public void RegistrandoUsuario(String nombreUsuarios, String login, String clave) {
Conector = Conecta.getConexion();
try {
String Query = "INSERT INTO 'sil'.'usuarios' ('nombreUsuarios',"
+ " 'login', 'clave') VALUES ('" + nombreUsuarios + "', '"
+ login + "', '" + clave + "');";
try (Statement St = Conector.createStatement()) {
St.executeUpdate(Query);
JOptionPane.showMessageDialog(null, "Datos ingresados correctamente!");
St.close();
Conector.close();
}
} catch (SQLException SQLe) {
JOptionPane.showMessageDialog(null, "Error en la consulta");
}
/*finally {
if (Conector != null) {
try {
Conector.close();
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error al cerrar la conexion");
Logger.getLogger(OperacionesLicorerias.class.getName()).log(Level.SEVERE, null, sqle);
}
}
}*/
}
public ResultSet BuscaUsuario(String login) {
Conector = Conecta.getConexion();
String Query = "SELECT * FROM sil.usuarios where login = ?";
Statement St = null;
ResultSet Rs = null;
PreparedStatement Pst = null;
try {
Pst = Conector.prepareStatement(Query);
Pst.setString(1, login);
Rs = Pst.executeQuery();
while (Rs.next()) {
JOptionPane.showMessageDialog(null, " | ID: " + Rs.getString("idUsuarios")
+ " | Login: " + Rs.getString("login")
+ " | Nombre: " + Rs.getString("nombreUsuarios"));
St.close();
Rs.close();
}*/
} catch (SQLException SQLe) {
JOptionPane.showMessageDialog(null, "Error en la consulta");
Logger.getLogger(OperacionesLicorerias.class.getName()).log(Level.SEVERE, null, SQLe);
}
return Rs;
}
public void BorraUsuario(String login) {
Conector = Conecta.getConexion();
try {
String Query = "DELETE FROM usuarios WHERE 'login'='" + login + "';";
Statement St = Conector.createStatement();
St.executeUpdate(Query);
JOptionPane.showMessageDialog(null, "Registro borrado con exito!");
St.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error en la actualizacion de datos");
} finally {
if (Conector != null) {
try {
Conector.close();
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error al cerrar la conexion");
Logger.getLogger(OperacionesLicorerias.class.getName()).log(Level.SEVERE, null, sqle);
}
}
}
}
}
Last night I was able to solve the problem, as you can see in my code, apparently I am building an object or instantiating a class, which is already running the connection, and I also created a Connection type object to which I tell it to execute the method .getConnection, modify the code and remove the getConnection () method from my Conexion class, added the connection type to my Conexion method and that's where the shots went.
To realize where my error was, I had to comment on the instructions where there were connection methods, step by step testing the project and discard what was causing me connections that did not close, and I could determine that the problem was in my Conexion class.
If there is any information that someone wants to ask me would be perfect, as you can see I am learning on my own and I still need to handle many topics.