在while循环中选择查询

时间:2015-08-17 14:29:19

标签: java hashmap resultset

我在While循环中有一个SELECT查询。我期待一排。在获得该行之后,我想从while循环中走出来。问题是,在第一次迭代后执行select查询并检查结果集时,我收到“Invalid Cursor”错误。不知道我在这里做错了什么。

//looping thru hashmap

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    int bind_index=1; 
    Map.Entry pair = (Map.Entry)it.next();
    log.debug(pair.getKey() + " = " + pair.getValue());

    String sql_main = null;
    sql_main = getSql(sb2.toString());
    ResultSet resultSet = null;
    PreparedStatement p_stmt1 = null;
    p_stmt1 = db.getPreparedStatement(sql_main);    

    p_stmt1.setString(bind_index++, (String)pair.getKey()); 
    p_stmt1.setString(bind_index++, (String)pair.getValue());   
    p_stmt1.setString(bind_index++,strGMTDate+" "+strGMTTime);
    p_stmt1.setString(bind_index++,strGMTDate+" "+strGMTTime);
    resultSet = db.executeQuery(p_stmt1);


    CachedRowSetImpl rsCopy2 = new CachedRowSetImpl();  
    rsCopy2.populate(resultSet);    
    if(rsCopy2.next()){
        rsCopy2.beforeFirst();
        grid.bind(rsCopy2);
        break;
    }
    resultSet = null;
    p_stmt1=null;
    resultSet.close();
    p_stmt1.close();
}

1 个答案:

答案 0 :(得分:0)

首先,由于您的SQL没有改变,您应该在循环之外准备语句。此外,您应该使用try-with-resources来确保清理JDBC资源。

此外,您的executeQuery错误。

String sql_main = getSql(sb2.toString());
try (PreparedStatement p_stmt1 = db.getPreparedStatement(sql_main)) {
    for (Map.Entry pair : map.entrySet()) {
        log.debug(pair.getKey() + " = " + pair.getValue());
        int bind_index = 0;
        p_stmt1.setString(++bind_index, (String)pair.getKey());
        p_stmt1.setString(++bind_index, (String)pair.getValue());
        p_stmt1.setString(++bind_index, strGMTDate + " " + strGMTTime);
        p_stmt1.setString(++bind_index, strGMTDate + " " + strGMTTime);
        try (ResultSet resultSet = p_stmt1.executeQuery()) {
            if (resultSet.next()) {

                // Capture/use values from resultSet here

                break;
            }
        }
    }
}