Tengo una base de datos con la cual me tengo que conectar con Java a través de una interfaz gráfica. Cuando intento introducir los datos correctos me salta una excepción (MySQLNonTransientConnectionException
), sin embargo si pongo datos falsos no salta la excepción y sale el mensaje correcto en un ContentPane
.
JButton buttonAceptar = new JButton("Aceptar");
buttonAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String login, password;
GestorUsuario gu = new GestorUsuario();
login = textFieldLog.getText().toString();
password = textFieldPass.getText().toString();
try {
if(gu.autenticar(login, password)){
textPaneEstado.setText("Existe el usuario: "+login
+" con contraseña: "+password);
}else{
textPaneEstado.setText("No existe usuario con esas características"
+ "\nIntroduzca un nuevo usuario, por favor.");
}
} catch (Exception e) {
e.printStackTrace();
textPaneEstado.setText("Excepción Capturada");
}
}
});
El método autenticar
de la clase GestorUsuario
es el siguiente:
public static boolean autenticar(String login, String password) throws Exception{
boolean autenticado = false;
if(Usuario.read(login, password) != null)
autenticado = true;
return autenticado;
}
Aquí a su vez se llama al método read
de la clase Usuario
:
//Seleccion de un usuario de la base de datos a partir del login y el password
public static Usuario read(String login, String password) throws Exception{
String l,g;
Usuario u = null;
Vector<Object> aux = null;
String SQL_Consulta = "SELECT login, pass FROM usuario WHERE login = '"+login+"' AND pass = '"+password+"';";
Agente a = Agente.getAgente();
Vector<Object> res = a.select(SQL_Consulta);
if (res.size() == 1){
aux = (Vector<Object>) res.elementAt(0);
u = new Usuario((String) aux.elementAt(0), (String) aux.elementAt(1));
}
return u;
}
La clase Agente
es la encargada de realizar las conexiones pertinentes a la base de datos:
//instancia del agente
protected static Agente mInstancia=null;
//Conexion con la base de datos
protected static Connection mBD;
//Identificador ODBC de la base de datos
private static String url="jdbc:mysql://localhost:3307/practicabd?user=alumno&password=alumno";
//Driven para conectar con bases de datos MySQL
private static String driver="com.mysql.jdbc.Driver";
public static Agente getAgente() throws Exception{
if (mInstancia==null){
mInstancia=new Agente();
}
return mInstancia;
}
//Metodo para realizar la conexion a la base de datos
private void conectar() throws Exception {
Class.forName(driver);
mBD=DriverManager.getConnection(url);
}
El método select
de esta clase, selecciona a partir de un query, los campos de la base de datos correspondientes:
public Vector<Object> select(String SQL) throws SQLException,Exception{
Vector <Object> vector = new Vector<>();
Usuario user = new Usuario();
ResultSet result = null;
conectar();
Statement stmt = mBD.createStatement(); // Sentencia una vez realizada la conexion con la base de datos
result = stmt.executeQuery(SQL);
try{
while (result.next()){
String login = result.getString("login");
String passwd = result.getString("pass");
vector.add(user.read(login, passwd));
}
}catch(SQLException ex){
ex.printStackTrace();
}
stmt.close();
desconectar();
return vector;
}
La base de datos tiene dos campos, uno en el que se almacena un "nombre de usuario" y otro en el que se almacena una contraseña. Los datos que tiene la base de datos son los siguientes:
1234 1234 aurora supassword Julián elpassword Nacho otropassword
He hecho una prueba de conexión con la base de datos para obtener estos valores y me resulta satisfactoria:
public class HolaMySQL {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("registro perfecto");
}catch(Exception e){
System.out.println("fallo en registro");
}
Connection con = null;
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3307/practicabd?user=alumno&password=alumno");
System.out.println("Conexión OK");
java.sql.Statement consulta = con.createStatement();
ResultSet r = consulta.executeQuery("SELECT * FROM practicabd.usuario;");
while(r.next()){
System.out.println(r.getString(1)+" "+r.getString(2));
}
} catch(SQLException ex){
System.out.println("error de conexión: "+ex.getMessage());
}
}
}
El error en cuestión que me sale es el siguiente:
Mon Oct 10 13:18:41 CEST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections" at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) at com.mysql.jdbc.Util.getInstance(Util.java:387) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:917) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1042) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083) at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:806) at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at persistencia.Agente.conectar(Agente.java:43) at persistencia.Agente.select(Agente.java:90) at dominio.Usuario.read(Usuario.java:32) at dominio.GestorUsuario.autenticar(GestorUsuario.java:8) at presentacion.JFrameLogin$2.actionPerformed(JFrameLogin.java:92) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)