Agonija Agonija - 6 months ago 15
SQL Question

not receiving right double value

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

Answer

shouldn't your query be

ResultSet rs = st.executeQuery("select price from products where name = '" + name + "';");

your current query does not seem to incorporate the input param and hence the resultset would have a null price value. let me know if this is not the case

Alternative is to use PreparedStatement where you can pass multiple parameters, but i don't think that's necessary here.

if you're interested,

http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

And a better way to check if the result set contains any results is to do this instead of next()

if (!rs.isBeforeFirst())