JDBC - does not connect to Mysql database

Asked

Viewed 698 times

4

In java I created a project in which I use the drive mysql-Connector-java-5.1.40-bin. jar, in this project I created a class with a form to register course and mysql I created a database called sistema with a table called curso with the fields:

inserir a descrição da imagem aqui

Then I created the following code within the button method Include to register the course:

    @Override
        public void actionPerformed(ActionEvent e){
if(e.getSource() == BIncluir){
    //procura a classe com.mysql.jdbc.Driver 
                try{
                    Class.forName("com.mysql.jdbc.Driver");

                    //cria uma variável:
                    Connection con;

                    //cria uma conexão com o banco de dados
                    con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/sistema", "root", "");

                    //minha query
                    String query = "INSERT INTO curso (cod_curso, nm_curso, tipo_curso, carga_h, cod_instituto) VALUES(?,?,?)";

                    //cria o camando
                    PreparedStatement stmt = con.prepareStatement(query);

                    //seta os valores na string de inserção
                    stmt.setString(1, CodCurso.getText());
                    stmt.setString(2, Txt1.getText());
                    stmt.setString(3, Txt2.getText());
                    stmt.setString(4, CargaHoraria.getText());
                    stmt.setString(5, CodInstituto.getText());

                    //executa o comando no banco de dados 
                    stmt.executeUpdate();

                    //fecha o comando e a conexão com o banco de dados
                    stmt.close();
                    con.close();

                } catch (ClassNotFoundException ex) { //tratador de erro do comando Class.forName
                    System.out.println("Não foi possível encontrar a classe");
                } catch (SQLException ex) { //tratador de erro do comando con = DriverManager.getConnection
                    System.out.println("Não foi possível conectar ao banco de dados");
                }

I did connection tests before including the query and it was connecting, but stopped connecting when it includes this part of the code that creates and runs the query:

//minha query
                String query = "INSERT INTO curso (cod_curso, nm_curso, tipo_curso, carga_h, cod_instituto) VALUES(?,?,?)";

                //cria o camando
                PreparedStatement stmt = con.prepareStatement(query);

                //seta os valores na string de inserção
                stmt.setString(1, CodCurso.getText());
                stmt.setString(2, Txt1.getText());
                stmt.setString(3, Txt2.getText());
                stmt.setString(4, CargaHoraria.getText());
                stmt.setString(5, CodInstituto.getText());

                //executa o comando no banco de dados 
                stmt.executeUpdate();

                //fecha o comando e a conexão com o banco de dados
                stmt.close();
                con.close();

When I press the Include button it shows the merge I set in Try catch: "Não foi possível conectar ao banco de dados" Please help me if you know!!!! : 0

  • Have the Exception printed (ex) in place of that description

  • You can change the fixed message from Sqlexception to ex.getMessage() so we can see the real error?

  • put so but n appears nothing: catch (Sqlexception ex) { ex.getMessage(); }

  • Put System.out.println(ex.getMessage());

  • ok fix now yes, this is the error q appeared: Parameter index out of range (4 > number of Parameters, which is 3).

  • Fine, then I’ll write the answer here for the record

  • ha found the error, is in values

  • I have 5 records and no values put only 3 VALUES(?,?,?)

Show 3 more comments

1 answer

4


Parameter index out of range (4 > number of Parameters, which is 3).

Your query has 3 parameters and you are trying to define 5 parameters. Ideally in error handling you use the message returned by the exception, so it will not hide the actual error.

System.out.println(ex.getMessage());
  • 1

    THANK YOU!!!!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.