java - SQL 代码的 NullPointerException 错误

标签 java mysql nullpointerexception

我有这个表单,其中包含三个文本字段和两个单选按钮。该表格应该计算客户的账单金额。我编写了以下代码,它显示 NullPointerException 错误。

int noproduct;
double totalprice, price, shipcharge;
try{
    Connection connection=getConnection();
    stmt=connection.createStatement();
    ResultSet rs1=stmt.executeQuery("Select count(ProductName) from buy;");
    ResultSet rs2=stmt.executeQuery("Select sum(price) as TPrice from buy;");
    noproduct=rs1.getInt("count(ProductName)");
    NoProducts.setText(""+noproduct);
    price=rs2.getDouble("TPrice");
    shipcharge=3 * noproduct;
    ShipCharges.setText(""+shipcharge);
    totalprice=price+shipcharge;
    TotalPrice.setText(""+totalprice);
    if(CashRB.isSelected()){
        totalprice=totalprice+(5*noproduct);
        JOptionPane.showMessageDialog(null,"You have paid the bill by Cash!");
    }
    else if(CCardRB.isSelected()){
        totalprice=totalprice-(5*noproduct);
        JOptionPane.showMessageDialog(null,"You have paid the bill using Credit Card!");
    }
}
catch(Exception ex){
    System.out.println(ex.toString());
    ex.printStackTrace();
}
finally{}

这一行具体显示了错误:

noproduct=rs1.getInt("count(ProductName)");

我需要一个替代代码来显示与此相同的结果。

它还显示了这些错误,我不太明白它们是什么:

java.lang.NullPointerException
        at com.mysql.jdbc.ResultSetImpl.buildIndexMapping(ResultSetImpl.java:709)
        at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1069)
        at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2734)

有人可以帮我吗?预先感谢您。

最佳答案

将其更改为

 rs1.next();
 noproduct=rs1.getInt(1);

see here

一个 Statement 允许有一个 ResultSet。在这种情况下你可能会遇到异常。因为您使用了 ResultSet res1 和 rs2。

关于java - SQL 代码的 NullPointerException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20179436/

相关文章:

android - Textview.settext() 给出空指针异常

java - 当 Vector 位于包含类中时,使用 Vector 的 addAll( ) 函数时出现问题

java - 为什么我需要在 tomcat 应用程序上启用 CORS

java - 移动椭圆以跟随光标java

php - 释放 PDO 准备好的语句 (DEALLOCATE PREPARE)

php - 动态 HTML 表格 - 更新单元格行

MySQL 查询具有最近日期的行

Java 8 计算最小值

java - OpenWeatherMap API : Encounter NullPointerException

java - 为什么我的 Spring @Autowired 字段为空?