新手指针rs.next

时间:2013-04-28 10:45:31

标签: java sql pointers conditional-statements resultset

我只想看到产品用户正在寻找它们,但是当第二个if被执行时它将推送(指针或其他任何东西)到下一个ID(我有唯一的id,所以它会推到无处)和结果为空。我希望你理解我的问题:)。

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

首先,您的方法容易受到SQL注入攻击。请参加PreparedStatement Look at this simple example for using PreparedStatement

你应该这样做:

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

答案 2 :(得分:0)

问题在于您正在阅读第一个结果,以便知道是否至少有一个结果,然后尝试使用下一个结果并丢失第一个结果(根据您的问题描述改编)。我解释了这是如何工作的here

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

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

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;