-1
public double getPrice(String name) throws SQLException {
    TechnoRepository repo = TechnoRepository.getInstance();
    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery("select price from products where name = '?';");
    if(rs.next())
       return rs.getDouble("price");   
    return 0;
}

Main class :

TechnoRepository repo = TechnoRepository.getInstance();
double price = repo.getPrice("water");
System.out.printf("%.2f",price);

Result is 0.0, not the right one

Clockwork-Muse
  • 12,806
  • 6
  • 31
  • 45
Agonija
  • 11
  • 2
  • 1
    Original code would not have compiled (`price` was not declared). Side note: `double`s can't store certain amounts, like `.1`, -exactly-, which can make accountants nervous. You should be storing anything money-related in a `BigDecimal` (Java), and `decimal`/`numeric` (SQL). – Clockwork-Muse May 28 '16 at 23:11

1 Answers1

3

You look to be trying to do a PreparedStatement, hence the question mark in the sql code.

However, since you are only creating a Statement you make your search in the table products where the name is equal to the literal ?. And since your table, presumably, does not contain a such character, there is no data in the ResultSet.

    public double getPrice(String name) throws SQLException {
        String sql = "select price from products where name = ?;";
        PreparedStatement prepStmt = connection.prepareStatement(sql);
        prepStmt.setString(1, name);

        ResultSet resultSet = prepStmt.executeQuery();

        double price = 0.0;
        if(rs.next())
            price = rs.getDouble("price");

        return price;
}

where prepStmt.setString(1, name); is where you replace with the first encountered ? with, in this case, the name.

Wisph
  • 204
  • 2
  • 6