Java 为什么在尝试对ResultSet中检索到的列的值求和时会出现错误?
我试图使用NETBeans IDE对SQL数据库中的一列的值求和。在表movimentacao中有一个列名valor,当我要执行代码时:Java 为什么在尝试对ResultSet中检索到的列的值求和时会出现错误?,java,mysql,database,jdbc,Java,Mysql,Database,Jdbc,我试图使用NETBeans IDE对SQL数据库中的一列的值求和。在表movimentacao中有一个列名valor,当我要执行代码时: ("Select SUM(valor) FROM movimentacao WHERE (id_categoria=" + id_categoria +")"); 控制台向我显示,此结果集中不存在此列,我使用两个结果集执行不同的操作,它们具有不同的名称 ResultSet rs = busca.getResultSet(); 及 有人知道这个错误的解决方法
("Select SUM(valor) FROM movimentacao WHERE (id_categoria=" + id_categoria +")");
控制台向我显示,此结果集中不存在此列,我使用两个结果集执行不同的操作,它们具有不同的名称
ResultSet rs = busca.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
}
您没有在查询中为SUM指定名称,因此列名为
SUM(valor)
notvalor
。如果您只访问结果的索引1,如rs.getDouble(1)
,或者使用正确的名称,只要查询本身有效,您就可以得到所需的名称。替换
soma=soma+rs.getDouble(“valor”)代码>带有
soma=soma+rs.getDouble(1)代码>
它会工作。确切的错误信息是什么?不要试图解释它,告诉我们确切的信息,因为信息通常会告诉你到底哪里错了,哪里错了。我问得对!我使用了Eric给出的答案,并且工作了…谢谢dude@HovercraftFullOfEelsSi verdad:)哦,我现在感觉很糟糕,称呼葡萄牙语,西班牙语就像称呼苏格兰英语。使用rs.getDouble(1)是可行的,但是使用rs.getDouble(SUM(valor))不可行……我会坚持使用索引,但是如果您想确定列名实际上是什么,您可以这样做:ResultSetMetaData rsmd=rs.getMetaData();String name=rsmd.getColumnName(1)代码>
/*
* 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());
}