Problem entering data with methods. Java/Mysql

Asked

Viewed 147 times

2

I get the following error when I try to add a new data into a table in my database. I have a class whose name is Banco de Dados , another whose name is ShowMenu and another whose name is Principal.

And I get the following mistake:

Exception in thread "main" java.lang.NullPointerException
    at BancoDeDados.addDespesa(BancoDeDados.java:27)
    at ShowMenu.novoTipo(ShowMenu.java:55)
    at ShowMenu.menu(ShowMenu.java:30)

I believe the error would be in the communication of methods addDesp with the novoTipo.

Showmenu.java

public void novoTipo() throws SQLException{
    BancoDeDados insertInto = new BancoDeDados();
    String nomeDesp;
    System.out.println("\nDigite o nome da despesa:");
    nomeDesp = teclado.next();
    insertInto.addDespesa(nomeDesp);
}

Bancodedados.java.

public class BancoDeDados {

private Statement comando;

public void conexao(){
    try {
        System.out.println("Conectando ao Banco de Dados..");
        Class.forName("com.mysql.jdbc.Driver");
        Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost:3306/despesas?useSSL=true","root","local");
        comando = conexao.createStatement();
        System.out.println("Conectado. \n");
    } catch (ClassNotFoundException | SQLException e) {
        System.out.println("Erro na Conexão");
    }
}

public void addDespesa(String addDesp) throws SQLException{
    String sqlInsert, sqlSelect;
    sqlInsert = "insert into tipo_de_despesa(descricao) values ('"+addDesp+"')";
    comando.execute(sqlInsert); 
}

}

  • Dude because you didn’t question the other question?

  • Sorry I thought I couldn’t have questioned it anyway.

  • You have not started the variable command, so it is null. The connected method needs to be called before the addDespesa method. You read the link I left in the other reply?

  • 1

1 answer

0

comando has never been initialized and you try to use

comando.execute(sqlInsert);

Hence the error occurs, because comando is null.

Before calling addDespesa, remember to initialize your object comando thus:

comando = conexao.createStatement();

Browser other questions tagged

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