java - 为什么在尝试对 ResultSet 中检索到的列的值求和时出现错误?

标签 java mysql database jdbc

我正在尝试使用 NETBeans IDE 对 SQL 数据库中列的值求和。在表 movimentacao 中有一个列名 valor,当我要执行代码时:

("Select SUM(valor) FROM movimentacao WHERE (id_categoria=" + id_categoria +")");

控制台向我显示此 ResultSet 中不存在此列,我正在使用两个 resultSet 来做不同的事情,它们具有不同的名称...

ResultSet rs = busca.getResultSet();

ResultSet rs2 = busca2.getResultSet(); 

有人知道这个错误的解决方案吗?完整代码下方:

  /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controle_financeiro;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.DefaultListModel;

/**
 *
 * @author IAGO
 */
public class TelaRelatorioCategoria extends javax.swing.JFrame {

    /**
     * Creates new form TelaRelatorioCategoria
     */
    public TelaRelatorioCategoria() {
        initComponents();
        ArrayList<String> dados = new ArrayList<String>();  
            String databaseURL = "jdbc:postgresql://localhost/db_controle_financeiro?user=us_iago&password=123";
            String driverName = "org.postgresql.Driver";
            Connection con;   
        try {
            Class.forName(driverName).newInstance();
            con = DriverManager.getConnection(databaseURL); 
            System.out.println("Conexão obtida com sucesso.");
            PreparedStatement input = null;  
            Statement st = con.createStatement();
            String sql = "Select nome from categoria"; 
            ResultSet rs = st.executeQuery(sql);
            DefaultListModel modelo = new DefaultListModel();
            while (rs.next()) {
                    String nomeProduto = rs.getString(1);
                    modelo.addElement(nomeProduto);
            }
            listaMovimentacaoRelatorio.setModel(modelo);
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } catch (Exception e) {
            System.out.println("Problemas ao tentar conectar com o banco de dados: " + e);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listaMovimentacaoRelatorio = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        botao_voltar = new javax.swing.JButton();
        botao_exibir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        listaMovimentacaoRelatorio.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(listaMovimentacaoRelatorio);

        jLabel1.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
        jLabel1.setText("Selecione as Categorias");

        botao_voltar.setText("Voltar");
        botao_voltar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botao_voltarMouseClicked(evt);
            }
        });

        botao_exibir.setText("Exibir");
        botao_exibir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botao_exibirMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(botao_voltar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE)
                        .addComponent(botao_exibir, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(botao_exibir, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                    .addComponent(botao_voltar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void botao_exibirMouseClicked(java.awt.event.MouseEvent evt) {                                          
        String valor_lista = listaMovimentacaoRelatorio.getSelectedValue().toString();
        String databaseURL = "jdbc:postgresql://localhost/db_controle_financeiro?user=us_iago&password=123";
        String driverName = "org.postgresql.Driver";
        Connection con;   
        try {
            Class.forName(driverName).newInstance();
            con = DriverManager.getConnection(databaseURL); 
            System.out.println("Conexão obtida com sucesso.");
            int id_categoria = 0;
            Statement busca = con.createStatement();
            String sql1 = ("select id from categoria where (nome = '" + valor_lista + "')");
            busca.executeQuery(sql1);
            ResultSet rs = busca.getResultSet();
            while (rs.next()) {
                    id_categoria = rs.getInt("id");      
            }   
            Statement busca2 = con.createStatement();
            String sql2 = ("Select SUM(valor) FROM movimentacao WHERE (id_categoria=" + id_categoria +")");
            busca2.executeQuery(sql2);
            double soma = 0;
            ResultSet rs2 = busca2.getResultSet();
            while (rs2.next()) {
                    soma = soma + rs.getDouble("valor");        
            }  
            System.out.println(soma);
            /*Statement busca2 = con.createStatement();
            String sql2 = ("Select nome from categoria where (id =" + id_categoria +")");
            busca2.execute(sql2);*/
        } catch (Exception e) {
                        System.err.println(e.getMessage());
        }

        Relatorio relatorio = new Relatorio();
        relatorio.setVisible(true);  
        dispose();
    }                                         

    private void botao_voltarMouseClicked(java.awt.event.MouseEvent evt) {                                          
        TelaExibirRelatório tela_exibir_relatorio = new TelaExibirRelatório();
        tela_exibir_relatorio.setVisible(true);  
        dispose();
    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorioCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorioCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorioCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorioCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaRelatorioCategoria().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton botao_exibir;
    private javax.swing.JButton botao_voltar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JList listaMovimentacaoRelatorio;
    // End of variables declaration                   
}

这是我正在谈论的代码部分

String valor_lista = listaMovimentacaoRelatorio.getSelectedValue().toString();
String databaseURL = "jdbc:postgresql://localhost/db_controle_financeiro?user=us_iago&password=123";
String driverName = "org.postgresql.Driver";
Connection con;   
try {
    Class.forName(driverName).newInstance();
    con = DriverManager.getConnection(databaseURL); 
    System.out.println("Conexão obtida com sucesso.");
    int id_categoria = 0;
    Statement busca = con.createStatement();
    String sql1 = ("select id from categoria where (nome = '" + valor_lista + "')");
    busca.executeQuery(sql1);
    ResultSet rs = busca.getResultSet();
    while (rs.next()) {
            id_categoria = rs.getInt("id");      
    }   
    Statement busca2 = con.createStatement();
    String sql2 = ("Select SUM(valor) FROM movimentacao WHERE (id_categoria=" + id_categoria +")");
    busca2.executeQuery(sql2);
    double soma = 0;
    ResultSet rs2 = busca2.getResultSet();
    while (rs2.next()) {
            soma = soma + rs2.getDouble("valor");        
    }  
    System.out.println(soma);
    /*Statement busca2 = con.createStatement();
    String sql2 = ("Select nome from categoria where (id =" + id_categoria +")");
    busca2.execute(sql2);*/
} catch (Exception e) {
                System.err.println(e.getMessage());
}

最佳答案

您没有在查询中为 SUM 命名,因此列名是 SUM(valor) 而不是 valor。如果您只是访问结果的索引 1,如 rs.getDouble(1),或者使用正确的名称,您将获得所需的结果,前提是查询本身正在运行。

关于java - 为什么在尝试对 ResultSet 中检索到的列的值求和时出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30280023/

相关文章:

java - Eclipse 中的类型未定义该方法

java - Android中使用的onPrepareOptionsMenu

java - 如何从 Java 迭代器中随机访问数据

java - 以编程方式在垂直 LinearLayout 内添加约束布局?

mysql - 在sql中打印奇数id的 'O'和偶数id的 'E'

php - 通过 AJAX 注入(inject)受控 HTML 是否是一个安全问题?

django - 在 Django 应用程序的数据库列中保存标签(逗号分隔)会使大数据库变慢

php - 获取包含相同其他列的所有 Mysql 列

php - 从内连接创建 mysql 表

database - 试图删除 (*) 和 (*) 之间的关系。但是,关系的外键之一 (X) 不能设置为 null