没有得到正确的双重价值

时间:2016-05-28 22:38:49

标签: java mysql

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;
}

主要课程:

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

结果是0.0,而不是正确的结果

1 个答案:

答案 0 :(得分:3)

您希望尝试执行PreparedStatement,因此在sql代码中出现问号。

但是,由于您只是创建了Statement,因此您可以在表products中进行搜索,其中名称等于文字?。由于您的表格可能不包含此类字符,因此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;
}

其中prepStmt.setString(1, name);是您第一次遇到?的地方,在这种情况下是name