[RESOLVIDO]Atualização no banco de dados

29 respostas
L

Bom dia, estou com um problema que não estou conseguindo resolver. O problema é o seguinte: Eu quero pegar o valor da linha que eu selecionei na coluna 2, somar com o campo 3 do meu banco de dados e fazer um update no mesmo campo 3. Sendo assim valorselecionado+valorcampo3 = o que eu quero, que é o que vai voltar pro campo 3. Segue o código. Gostaria que me alertassem do que estou fazendo de errado.

public void atualizabanco(){
                String sql = "Select * from estoque where id=?";
                String sql1 = "Update estoque set qtd=? where id=?";
        try {
            pst = conexao.prepareStatement(sql);
            pst.setString(1, campoid.getText());
            rs = pst.executeQuery();
            if (rs.next()) {
            }
            int soma;
            int qtd = Integer.parseInt(rs.getString(3));
            int linhaSelecionada = jTable1.getSelectedRow();
            int coluna = 2;
            int valorSelecionado = (Integer) jTable1.getValueAt(linhaSelecionada, coluna);
            soma = qtd + valorSelecionado;
            pst = conexao.prepareStatement(sql1);
            pst.setString(1, Integer.toString(soma));
            pst.setString(2, campoid.getText());
            pst.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

29 Respostas

smatt

Seu if está vazio :thinking:

L

eu acho que n tem algo a ver com meu erro não.

smatt

Pode até não ter, mas que if vazio tá errado, isso eu te garanto kk não faz sentido algum ele ser vazio. É como se lêssemos: " se rs.next() resultar true, não faça nada ". Qual a lógica de você ver se existe algo no ResultSet e não fazer nada com ele? :thinking:

L

Tudo bem, a gente ta aqui pra aprender kkk

smatt

Com certeza kkk até eu também estou, mas é bem lógico o if vazio ser um erro. Tente dessa forma:

try {
            pst = conexao.prepareStatement(sql);
            pst.setString(1, campoid.getText());
            rs = pst.executeQuery();
            if (rs.next()) {
            int soma;
            int qtd = Integer.parseInt(rs.getString(3));
            int linhaSelecionada = jTable1.getSelectedRow();
            int coluna = 2;
            int valorSelecionado = (Integer) jTable1.getValueAt(linhaSelecionada, coluna);
            soma = qtd + valorSelecionado;
            }
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    
    try {
    pst = conexao.prepareStatement(sql1);
                pst.setString(1, Integer.toString(soma));
                pst.setString(2, campoid.getText());
                pst.executeUpdate();
    } catch (Exception e) {
                throw new RuntimeException(e);
   }

}

L

assim da erro na variavel soma

smatt
Tenta assim:

        try {
        pst = conexao.prepareStatement(sql);
        pst.setString(1, campoid.getText());
        rs = pst.executeQuery();
        if (rs.next()) {
        int soma;
        int qtd = Integer.parseInt(rs.getString(3));
        int linhaSelecionada = jTable1.getSelectedRow();
        int coluna = 2;
        int valorSelecionado = (Integer) jTable1.getValueAt(linhaSelecionada, coluna);
        soma = qtd + valorSelecionado;
        }            
   
        pst = conexao.prepareStatement(sql1);
            pst.setString(1, Integer.toString(soma));
            pst.setString(2, campoid.getText());
            pst.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
L

continua o mesmo erro

smatt

Posta o StackTrace por gentileza.

L

Exception in thread “AWT-EventQueue-0” java.lang.RuntimeException: java.lang.RuntimeException: java.lang.ArrayIndexOutOfBoundsException: -1

rodriguesabner

Em qual linha? E o que tem nessa linha?


int linhaSelecionada = jTable1.getSelectedRow();
  int coluna = 2;

Isso aqui não tem necessidade, você substituir por:

jTable1.getValueAt(jTable1.getSelectedRow(), 2);
smatt

Cola aqui o StackTrace completinho meu caro, por gentileza.

L
Exception in thread AWT-EventQueue-0 java.lang.RuntimeException: java.lang.RuntimeException: java.lang.ArrayIndexOutOfBoundsException: -1

at GUI.VendaProd.remove(VendaProd.java:135)

at GUI.VendaProd.jButton2ActionPerformed(VendaProd.java:566)

at GUI.VendaProd.access$1700(VendaProd.java:11)

at GUI.VendaProd$14.actionPerformed(VendaProd.java:459)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)

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:6539)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)

at java.awt.Component.processEvent(Component.java:6304)

at java.awt.Container.processEvent(Container.java:2239)

at java.awt.Component.dispatchEventImpl(Component.java:4889)

at java.awt.Container.dispatchEventImpl(Container.java:2297)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)

at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)

at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)

at java.awt.Container.dispatchEventImpl(Container.java:2283)

at java.awt.Window.dispatchEventImpl(Window.java:2746)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)

at java.awt.EventQueue.access$500(EventQueue.java:97)

at java.awt.EventQueue$3.run(EventQueue.java:709)

at java.awt.EventQueue$3.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)

at java.awt.EventQueue$4.run(EventQueue.java:733)

at java.awt.EventQueue$4.run(EventQueue.java:731)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Caused by: java.lang.RuntimeException: java.lang.ArrayIndexOutOfBoundsException: -1

at GUI.VendaProd.atualizabanco(VendaProd.java:159)

at GUI.VendaProd.remove(VendaProd.java:133)

 39 more

Caused by: java.lang.ArrayIndexOutOfBoundsException: -1

at java.util.Vector.elementData(Vector.java:737)

at java.util.Vector.elementAt(Vector.java:480)

at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)

at javax.swing.JTable.getValueAt(JTable.java:2720)

at GUI.VendaProd.atualizabanco(VendaProd.java:150)

 40 more
smatt

ArrayIndexOutOfBounds ocorre quando quer acessar uma posição inexistente de um vetor :thinking:

Na classe VendaProd, linha 135 que está ocorrendo o erro. O que tem nessa linha?

L

throw new RuntimeException(e);

L

Cara o problema está nesse método aí mesmo. Algo não estou acertando.

rodriguesabner

Faz o teste básico pra ver se ta pegando o valor da tabela mesmo, pode colocar esse código isolado mesmo, sem conexão. Você vai clicar na tabela e apertar em um botão e ele tem que mostrar o resultado

Coloca isso em um botão

String linha = "" + tabela.getValueAt(tabela.getSelectedRow(), 1);
    System.out.println(linha);
L

Tá funcionando sim.

rodriguesabner

Agora vai fazendo os passos, tenta fazer a soma com alguma variável padrão mesmo, pode ser tudo via console.

Tipo:

private int get_table_result(){
   int resultado;
      String linha = "" + tabela.getValueAt(tabela.getSelectedRow(), 1);
      int valor = Integer.parseInt(linha);
      resultado = valor + get_result();
   return resultado;
}

O resultado acima é CERTEZA que funciona, depois é só você pegar o resultado e fazer o SELECT com o banco.

private int get_result(){
    int qtd;
       try {
            conecta.executaSQL("select * from tabela where id='" + campoid.getText() + "'");
            conecta.rs.first();
            qtd = conecta.rs.getInt("qtd");
        } catch (SQLException s) {
            s.printStackTrace();
        }
     return qtd;
}

public update_database(){
    .......
}
L

Bom dia, ficou assim e continua a mesma coisa, dando o mesmo erro.

private int get_table_result() {
        int resultado;
        String linha = "" + jTable1.getValueAt(jTable1.getSelectedRow(), 1);
        int valor = Integer.parseInt(linha);
        resultado = valor + get_result();
        return resultado;
    }

    private int get_result() {
        String sql = "Select * from estoque where id=?";
        int qtd = 0;
        try {
            pst = conexao.prepareStatement(sql);
            pst.setString(1, campoid.getText());
            rs = pst.executeQuery();
            while (rs.next()) {
                qtd = Integer.parseInt(rs.getString(3));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return qtd;
    }

    public void atualizabanco() {
        String sql1 = "Update estoque set qtd=? where id=?";

        try {
            pst = conexao.prepareStatement(sql1);
            pst.setString(1, Integer.toString(get_table_result()));
            pst.setString(2, campoid.getText());
            pst.executeUpdate();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
rodriguesabner

Você tá clicando na tabela antes?

L

Sim

L

Esse erro não faz sentido.

rodriguesabner

Qual método você tá chamando depois de clicar na tabela?

get_table_result() e get_result() é interessante você colocar quando clicar na tabela.

Já o atualizabanco() você pode colocar quando clicar no botão.

L

Acho que não tem a ver com isso não, os métodos já estão sendo chamados no atualizabanco(), não é preciso colocar para quando clicar na tabela. Observe, eu tenho esse código para diminuir do meu banco o que eu adiciono na tabela, é quase a mesma coisa e funciona, esse que a gente está tentando não está funcionando.

public void consultaproduto() {
    String sql = "Select * from estoque where id=?";
    try {
        pst = conexao.prepareStatement(sql);
        pst.setString(1, campoid.getText());
        rs = pst.executeQuery();

        while (rs.next()) {
            int qtd = Integer.parseInt(rs.getString(3));
            double soma = 0;
            for (int i = 0; i < jTable1.getRowCount(); i++) {
                int valorAux = (int) jTable1.getValueAt(i, 2);
                soma += valorAux + 1;
            }
            if (campoqtd.getText() == rs.getString(3) + 1) {
                JOptionPane.showMessageDialog(null, "Não temos esta quantidade em estoque, a quantidade do produto é: " + qtd, "Atenção!", JOptionPane.WARNING_MESSAGE);
            } else {
                if (soma <= qtd) {
                    adiciona();
                    String sql1 = "Update estoque set qtd=? where id=?";
                    try {
                        int qtd1 = Integer.parseInt(campoqtd.getText());
                        int subtracao = qtd - qtd1;

                        pst = conexao.prepareStatement(sql1);
                        pst.setString(1, Integer.toString(subtracao));
                        pst.setString(2, campoid.getText());
                        pst.executeUpdate();

                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Não temos esta quantidade em estoque, a quantidade do produto é: " + qtd, "Atenção!", JOptionPane.WARNING_MESSAGE);
                }
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Erro ao calcular Total Produtos: " + e.getMessage());
    }
}

e o erro é sempre o mesmo java.lang.ArrayIndexOutOfBoundsException: -1

smatt

Isso daí é um catch. Por acaso este catch é o try-catch que você acessa o BD ou conecta ao BD? Mande o try-catch completo que ocorre este erro por gentileza.

L

nenhum dos 2, esse catch é de outro método onde eu chamo o atualizabanco(), esse método onde está dando erro, é o que remove a linha e faz a subtração, jogando o valor para uma textfield, estou chamando o atualizabanco(), nele pois quero que quando remova a linha, o valor adicionado volte para o banco.

L

Alguém ajuda?

smatt

@Luiz_Henrique22 Chamei no seu inbox, verifique no seu perfil.

Criado 3 de junho de 2019
Ultima resposta 4 de jun. de 2019
Respostas 29
Participantes 3