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?
– user28595
Sorry I thought I couldn’t have questioned it anyway.
– Goji Berry
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?
– user28595
Related: Searching another Java Class table method variable
– user28595