0

我只想看到产品用户正在寻找它们,但是当第二个 if 执行时,它将推送(指针或那里的任何东西)到下一个 ID(我拥有唯一的 ID,因此它将推送到无处)并且结果为 null . 我希望你能理解我的问题:)。

    if (stmt.execute(
                        "SELECT * FROM products where ID=" + removeName)) {
                    rs = stmt.getResultSet();
    if (!rs.next()) {
                       m = "ID not found.";
                        return m;
                   }
4

3 回答 3

1

在您的情况下,您可以使用PreparedStatement来避免SQL 注入问题。

  PreparedStatement prodsQuery= con.prepareStatement("SELECT * FROM products where ID=?");
  prodsQuery.setInt(1,removeName);
  ResultSet rs = prodsQuery.executeQuery();
  if(!rs.next())
  {
        m = "ID not found.";
        return m;
   }
于 2013-04-28T10:53:53.433 回答
0

问题是您正在阅读第一个结果以了解是否至少有一个结果,然后尝试使用下一个结果并错过第一个结果(改编自您的问题描述)。我在这里解释了它是如何工作的。

此问题的一个可能解决方案是假设查询执行没有问题并且您有结果,然后检索数据(或List数据)并作为最后一步验证数据是否不为空或List数据不为空。

改编自Naveen 的答案的代码以显示建议的解决方案

PreparedStatement prodsQuery =
    con.prepareStatement("SELECT * FROM products where ID=?");
prodsQuery.setInt(1,removeName);
ResultSet rs = prodsQuery.executeQuery();
  1. 假设只有一个结果可以得到:

    //also assuming you will set the results in a Data class (yes, this can be replaced)
    Data data = null;
    if (rs.next()) {
        //logic to retrieve data...
        data = new Data();
        data.setSomething(rs.get(1));
        //more and more code to fill the data...
    
        //because it looks that you need it as String (wonder why you return a String as well)
        return data.toString();
    }
    //note: I use an else statement to check if indeed there were no results at all
    //else statement added using a line separator for code explanation purposes
    else {
        m = "ID not found.";
        return m;
    }
    
  2. 假设有一个要获得的结果列表:

    //also assuming you will set the results in a Data class (yes, this can be replaced)
    List<Data> dataList = new ArrayList<Data>();
    while (rs.next()) {
        //logic to retrieve data...
        Data data = new Data();
        data.setSomething(rs.get(1));
        //more and more code to fill the data...
    
        //because it looks that you need it as String (wonder why you return a String as well)
        dataList.add(data);
    }
    //in this case, there's no validation in order to know if there's any result
    //the validation must be in the client of this class and method checking if
    //the result list is empty using if(!List#isEmpty) { some logic... }
    return dataList;
    
于 2013-04-28T13:47:49.353 回答
0

首先,您的方法容易受到 SQL 注入的攻击。请前往 PreparedStatement。
看看这个使用 PreparedStatement 的简单示例

你应该这样做:

ResultSet rs = stmt.executeQuery("SELECT * FROM products where ID=" + removeName);
if (!rs.next()) {
      m = "ID not found.";
      return m;
}
于 2013-04-28T10:47:28.357 回答