Problem inserting data with methods. Java / Mysql

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 error:

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 communicating methods addDesp with 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); 
}

}

    
asked by anonymous 16.09.2017 / 21:53

1 answer

0

comando has never been initialized and you try to use

comando.execute(sqlInsert);

This is where the error occurs because comando is null .

Before calling addDespesa , remember to initialize your comando object like this:

comando = conexao.createStatement();
    
26.09.2017 / 13:04