![](/img/trans.png)
[英]Why do I get an error when trying to sum values of a column retrieved in a ResultSet?
[英]Why do I get an error when trying to sum values of a column retrieved in a ResultSet?
我正在嘗試使用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)
,或使用正確的名稱,只要查詢本身可以正常工作,就可以得到所需的名稱。
更換
soma = soma + rs.getDouble("valor");
與soma = soma + rs.getDouble(1);
它將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.