为什么这个java代码无法通过给定的整数检索某些内容?

时间:2014-11-06 15:06:06

标签: java mysql web-services

我试图编写这个程序,通过一个名为" NumOfServings"的给定整数变量来检索MySQL中的路径/多个路径。我似乎无法出于某种原因让它发挥作用:

@Path("/recipes/{NumOfServings}")
@GET
@Produces("text/plain")
public String getRecipesByServingSize(@PathParam("NumOfServings") String ourServingSize) throws SQLException,  

ClassNotFoundException
{
    int checkServingSize = 0;
    try {
        checkServingSize = Integer.parseInt(ourServingSize);
    }catch (NumberFormatException FAIL) {
        checkServingSize = 1;
    }
    String connectStr="jdbc:mysql://localhost:3306/fooddb";
    String username="root";
    String password="csci330pass";
    String driver="com.mysql.jdbc.Driver";
    Class.forName(driver);
    Connection con = DriverManager.getConnection(connectStr, username, password);
    String sql = "Enter in a Recipe ID from Recipe database, WHERE ID = ?";
    PreparedStatement prepStmt = con.prepareStatement(sql);
    if (ourServingSize >= 6)
    {
        prepStmt.setInt(1, ourServingSize);
        ResultSet rs = prepStmt.executeQuery();
    }
    else
    {
        prepStmt.setInt(0, ourServingSize);
        ResultSet rs = prepStmt.executeQuery();
    }
    String result = "";
    while (rs.next()) 
    {
        int recipeID3 = rs.getInt("RecipeID");
        String recipeName3 = rs.getString("RecipeName");
        String recipeType3 = rs.getString("RecipeType");
        String instructions3 = rs.getString("Instructions");
        int amtServings3 = rs.getInt("NumOfServings");
        int timeMinutes3 = rs.getInt("TotalTimeInMinutes");
        result += "ID: "+recipeID3+ "\n" +
                "Name: "+recipeName3+ "\n" +
                "Type: "+recipeType3+ "\n" +
                "Instructions: "+instructions3+ "\n" +
                "Total Servings: "+amtServings3+ "\n" +
                "Total Time: "+timeMinutes3+ "\n" + "\n";
    }
    return result;
}

我已经尝试了If - Else语句和while循环,但我无法在不向我吐出一系列错误的情况下使用它。这段代码究竟出了什么问题?究竟缺少什么导致我这些错误?

1 个答案:

答案 0 :(得分:0)

prepStmt.setInt(0, ourServingSize);错了

您应始终使用prepStmt.setInt(1, ourServingSize);,因为1是第一个参数的索引。