Access database connection using java

Asked

Viewed 73 times

2

I’m a beginner in java programming, and I’m trying to make a program that connects to a database and saves the information there. I created a specific class for the connection and created a method to insert the data, but it is falling in the catch and returning null. This code I found partial on the internet and changed to my need.

public void Insere(Cadastro cliente )
{
    if ((cliente.getNome() != null) && (cliente.getOS() != null) && (cliente.getDataEnt() != null) && (cliente.getMarca() != null) && (cliente.getModelo() != null) && (cliente.getNS() != null) && (cliente.getValor() != null) && (cliente.getDataOrc() != null))
    {
    try 
    {
        PreparedStatement strComandoSQL;
        strComandoSQL = conexao.prepareStatement("INSERT INTO Entrada(cod, Nome, Os, dataEnt, Marca, Modelo, NS, Valor, dataOrc) VALUES(?,'?','?','?','?','?','?','?','?')");
        strComandoSQL.setInt(1,cliente.getCod());
        strComandoSQL.setString(2,cliente.getNome());
        strComandoSQL.setString(3,cliente.getOS());
        strComandoSQL.setString(4,cliente.getDataEnt());
        strComandoSQL.setString(5,cliente.getMarca());
        strComandoSQL.setString(6,cliente.getModelo());
        strComandoSQL.setString(7,cliente.getNS());
        strComandoSQL.setString(8,cliente.getValor());
        strComandoSQL.setString(9,cliente.getDataOrc());
        int intRegistro = strComandoSQL.executeUpdate();
            if (intRegistro != 0){
            JOptionPane.showMessageDialog(null,"Registro adicionado !",
            "Mensagem",JOptionPane.INFORMATION_MESSAGE);
            comando.close();
            conexao.close();
            }
            else
            {
            JOptionPane.showMessageDialog(null,"Registro nao adicionado !",
            "Mensagem",JOptionPane.INFORMATION_MESSAGE);
            comando.close();
            conexao.close();
            }

}
catch (Exception Excecao) 
{
    JOptionPane.showMessageDialog(null,"SQLException: " +
    Excecao.getMessage(),"Erro: Selecao de registro",
    JOptionPane.INFORMATION_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null,"Falta Preencher Campo!",
"Mensagem",JOptionPane.INFORMATION_MESSAGE);
}
}

Does anyone know why it’s returning null?

The exception that is returning is "null"

The stack of errors:

java.lang.NullPointerException
    at planilha.Banco.Insere(Banco.java:52)
    at planilha.Planilha.actionPerformed(Planilha.java:102)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6516)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6281)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4872)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
    at java.awt.EventQueue.access$300(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.awt.EventQueue$3.run(EventQueue.java:704)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:720)
    at java.awt.EventQueue$4.run(EventQueue.java:718)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

Here the method connects

public void Conecta()
{
    //JOptionPane.showMessageDialog(null, "Preparando para iniciar a conexão com o BD;");

try
{
    /* Tenta se conectar ao Driver */
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}
catch (ClassNotFoundException e)
{
    JOptionPane.showMessageDialog(null, "Impossível carregar o Driver.");
    System.exit(0);
}
try
{
    /* nomedobanco é o nome que você deu anteriormente ao seu alias */
    conexao = DriverManager.getConnection("jdbc:odbc:Camptecnica");
    comando = conexao.createStatement();

}
catch (SQLException sqle)
{
    JOptionPane.showMessageDialog(null, "Problema ao conectar!");
    System.exit(0);
}
 //JOptionPane.showMessageDialog(null, "Conectado com sucesso!");

}
  • Welcome(a) to Stack Overflow in English! You can post the exception that is occurring??

  • Leonardo, post the stack of errors in the question. Preferably, add in your catch a Excecao.printStackTrace();

  • Where is line 52??

  • is that of the bank command "(strComandoSQL = connected.prepareStatement("INSE...."

  • Your connection is coming null. The origin of the problem does not seem to be well in this method. Make sure you are properly starting the connection before creating a Statement.

  • @diegofm you tell the connection to the bank? Because it has another method, and in it is successfully returning the connection.

  • Leonardo, by the error posted, the connection was not started, the variable conexao is null, so the error. You need to start the connection.

  • @diegofm did the test here, really, in the method inserts (), the connected variable is empty. But I did in the method connects () is getting the value. It’s like cleaning up after exiting the method. Any hint of what might be happening?

  • Are you calling the connect method before the inserts() method? Add it to the question just for the conference. Ah if possible, add the snippet where you invoke the inserts()(it doesn’t have to be all, just a snippet with that call)

  • @diegofm connects it () is being called in the main of another class and inserts it into a button of that same class.

Show 5 more comments
No answers

Browser other questions tagged

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