Erro Java “constructor 'X' in class 'X' cannot be applied to given types;”

1 resposta Resolvido
java
A

Ao compilar o código abaixo recebo o seguinte erro:

Exception in thread “AWT-EventQueue-0” java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Connection.ConnectionMySQL.

E na linha public class DAOusuario extends ConnectionMySQL {mostra isso na “dica”

constructor ConnectionMySQL in class ConnectionMySQL cannot be applied to given types; required: String, String, String, String

found: no arguments

reason: actual and formal arguments list differ in lenght

acredito que seja alguma incompatibilidade com o codigo ser int e o nome, email e senha ser String. Porém não consegui identificar como solucionar o erro

package Usuario;

import Connection.ConnectionMySQL;
import Modelo.ModeloUsuario;


/**
 *
 * @author [telefone removido]
 */
public class DAOusuario extends ConnectionMySQL {



       // grava o usuário

     public int salvarUsuario(ModeloUsuario pModelUsuario){
        try {
            this.conectar();
                return this.insertSQL(
                "INSERT INTO usuario("
                    + "nome,"
                    + "email,"
                    + "senha"
                + ") VALUES ("
                    + "'" + pModelUsuario.getNome() + "',"
                    + "'" + pModelUsuario.getEmail() + "',"
                    + "'" + pModelUsuario.getSenha() + "'"
                + ");"
            );
        }catch(Exception e){
            e.printStackTrace();
            return 0;
        }finally{
            this.fecharConexao();
        }
  }//Recupera DAOusuario
  public ModeloUsuario getUsuario(int pCodigo){
      ModeloUsuario modeloUsuario = new ModeloUsuario();
      try{
          this.conectar();
          this.executarSQL(
                    "SELECT "
                        + "codigo,"
                        + "nome,"
                        + "email,"
                        + "senha"
                    + "FROM"
                        + "usuario"
                    + "WHERE"
                        + "codigo= '" + pCodigo +"'"
                     +";"
          );
          while(this.getResultSet().next()){
                modeloUsuario.setCodigo(this.getResultSet().getInt(1));
                modeloUsuario.setNome(this.getResultSet().getString("admin"));
                modeloUsuario.setEmail(this.getResultSet().getString("admin"));
                modeloUsuario.setSenha(this.getResultSet().getString("admin"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            this.fecharConexao();
        }
        return modeloUsuario;
      }


    // código para login
   public ModeloUsuario getUsuario(String pEmail){
      ModeloUsuario modelUsuario = new ModeloUsuario();
        try {
            this.conectar();
            this.executarSQL(
                "SELECT "
                    + "codigo,"
                    + "nome,"
                    + "email,"
                    + "senha"
                 + " FROM"
                     + " usuario"
                 + " WHERE"
                     + " email = '" + pEmail + "'"
                + ";"
            );

            while(this.getResultSet().next()){
                modelUsuario.setCodigo(this.getResultSet().getInt(1));
                modelUsuario.setNome(this.getResultSet().getString(2));
                modelUsuario.setEmail(this.getResultSet().getString(3));
                modelUsuario.setSenha(this.getResultSet().getString(4));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            this.fecharConexao();
        }
        return modelUsuario;
    }



   public boolean getUsuario(ModeloUsuario pModelUsuario){       
        try {
            this.conectar();
            this.executarSQL(
                    "SELECT "
                    + "codigo,"
                    + "email,"
                    + "senha"
                    + " FROM"
                    + "usuario"
                    + " WHERE"
                    + " email = '" + pModelUsuario.getEmail()+ "' AND senha = '" + pModelUsuario.getSenha() + "' "
                    + ";"
            );

            if (getResultSet().next()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            this.fecharConexao();
        }      
    }
}

` Classe ConnectionMySQL
package Connection;

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

/**
 *
 * @author [telefone removido]
 */
public class ConnectionMySQL {
    public Connection con = null; // Conexão a aplicação ao Banco de Dados
    private boolean status = false;
    private String msg = ""; //Informar o status da conexão
    private Statement stmt; //Executa o comando SQL do driver
    private ResultSet resultSet; //Consultar a Base de Dados

    //Variáveis de conexão ao servidor de Banco de Dados
    private String servidor = "localhost";
    private String banco = "sisacai";
    private String usuario = "root";
    private String senha = "root";

    public ConnectionMySQL(String pServidor, String pBanco, String pUsuario, String pSenha){
        this.servidor = pServidor;
        this.banco = pBanco;
        this.usuario = pUsuario;
        this.senha = pSenha;
    }



    public Connection conectar() throws InstantiationException, IllegalAccessException, SQLException{
        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();

            //local do banco, nome do banco, usuátio e senha
            String url = "jdbc:mysql://" + servidor + "/" + banco;
            this.setCon((Connection)DriverManager.getConnection(url, usuario, senha));
            this.status = true;
        }

        catch(ClassNotFoundException e){
            JOptionPane.showMessageDialog(null,e.getMessage());
        }
        return this.getCon();
    } 

    //dc executa consultas SQL
    public boolean executarSQL(String pSQL){
        try{
            this.setStmt((Statement)getCon().createStatement());
            this.setResultSet(getStmt().executeQuery(pSQL));
        }

        catch (SQLException ex){
            ex.printStackTrace();
            return false;
        }
        return true;
    }
    // Executa Insert SQL
    public int insertSQL(String pSQL){
        int status = 0;
        try{
            //create Statement de con para criar o Statement
            this.setStmt((Statement)getCon().createStatement());

            //Definido o Statement, executamos a query no banco de dados
            this.getStmt().executeUpdate(pSQL);

            //Consulta o último id inserido
            this.setResultSet(this.getStmt().executeQuery("SELECT last_insert_id();"));

            //Recupera o último id inserido
            while(this.resultSet.next()){
                status = this.resultSet.getInt(1);
            }
            //Retorna o último id inserido
            return status;
        }

        catch(SQLException ex){
            ex.printStackTrace();
            return status;
        }
    }

    //Encerra a concexão corrente
     public boolean fecharConexao(){
         try{
             if((this.getResultSet() != null) && (this.stmt != null)){
                 this.getResultSet().close();
                 this.stmt.close();
             }
             this.getCon().close();
             return true;
         }
         catch(SQLException e){
             JOptionPane.showMessageDialog(null,e.getMessage());
         }
         return false;
     }

     //Métodos de seleção e modificação
     public Statement getStmt(){
         return stmt;
     }

     public void setStmt(Statement stmt){
         this.stmt = stmt;
     }

     public ResultSet getResultSet(){
         return resultSet;
     }

     public void setResultSet(ResultSet resultSet){
         this.resultSet = resultSet;
     }

     public Connection getCon(){
         return con;
     }

     public void setCon(Connection con){
         this.con = con;
     }

     public void setMensagem(String mensagem){
         this.msg = mensagem;
     }

     public String getMensagem(){
         return msg;
     }

     public boolean isStatus(){
         return this.status;
     }

     public String getServidor(){
         return servidor;
     }

     public void setServidor(String servidor){
         this.servidor = servidor;
     }

     public String getNomeDoBanco(){
         return banco;
     }

     public void setNomeDoBanco(String nomeDoBanco){
         this.banco = nomeDoBanco;
     }

     public String getUsuario(){
         return usuario;
     }

     public void setUsuario(String usuario){
         this.usuario = usuario;
     }

     public String getSenha(){
         return senha;
     }

     public void setSenha(String senha){
         this.senha = senha;
     }
}

1 Resposta

S
Solucao aceita

O erro acontece pois sua classe ConnectionMySQL define o seguinte construtor:

public ConnectionMySQL(String pServidor, String pBanco, String pUsuario, String pSenha) {
    this.servidor = pServidor;
    this.banco = pBanco;
    this.usuario = pUsuario;
    this.senha = pSenha;
}

E no construtor da classe DAOusuario você não está chamando o construtor da superclasse.

Mas tenho algumas perguntas:

Porque sua classe DAOusuario estende a classe ConnectionMySQL?
Pergunto isso pois um DAO não é uma conexão com o banco, ele tem uma conexão com o banco.

Porque você precisa de getters e setters dos parâmetros que você obrigatoriamente tem que informar no construtor da classe ConnectionMySQL?

Por que você precisa de getters e setters para o PreparedStatement na classe ConnectionMySQL?

Por que você precisa de getters e setters para o ResultSet na classe ConnectionMySQL?

Criado 12 de novembro de 2018
Ultima resposta 12 de nov. de 2018
Respostas 1
Participantes 2