0

Java - Netbeans IDE

I have this code but the variable Priceperitem is not found, can anyone explain? or show me an easier way of selecting a record from a table in a database and setting its value as a variable?

Price P/Item is the name of column within the database table.

    String sql = "SELECT Price P/Item FROM tblResources";
 try {

pst = conn.prepareStatement(sql);

        rs = pst.executeQuery();

       while (rs.next()){

      double Priceperitem = rs.getDouble("Price P/Item");

       }

  } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "Runtime Error");
    }

and then :

try {

 Total = Quantity * Priceperitem;       (This is where Priceperitem is not found.)

   btnCalculateTotal.setText("Total: £"+Total+"0");

 }catch (Exception e){

     System.out.println("Error Calculating Total");
}
2
  • Does that SQL execute when run directly on the database? If that really is the column name, then you'll need to escape it in your query to prevent the database misinterpreting it. Commented Jan 23, 2014 at 10:26
  • To start i would suggest modifying Database column name instead of P/Item -> Per_Item Commented Jan 23, 2014 at 11:25

1 Answer 1

1

You have declared Priceperitem locally within the while loop. It is not visible outside the loop.

To fix this, move the declaration to to the outer level:

double Priceperitem = 0;

Side note: you should respect the Java naming conventions. So a better name is pricePerItem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.