0

I was about to display questions and their respective options from the questionsDB and optionsDB. I have create two result sets and two queries to do the stuff in nested loop.It works fine in first iteration by displaying the first question and its respective options but after that its not iterating the data.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.sql.*"%> <% String driverName = "com.mysql.jdbc.Driver"; String connectionUrl = "jdbc:mysql://localhost:3306/"; String dbName = "onlinefeedback"; String userId = "root"; String password = "123456"; try { Class.forName(driverName); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection connection = null; Statement statement = null; ResultSet resultQuestions = null; ResultSet resultOptions = null; try{ connection = DriverManager.getConnection(connectionUrl+dbName, userId, password); statement=connection.createStatement(); String qsql ="SELECT * FROM questionsDB"; resultQuestions = statement.executeQuery(qsql); while(resultQuestions.next()) { int curQuestion= Integer.parseInt(resultQuestions.getString("qid")); %> <%= resultQuestions.getString("qid") %> <%=resultQuestions.getString("questionmessage") %> <% String osql ="SELECT * FROM optionsDB WHERE qid="+curQuestion; resultOptions = statement.executeQuery(osql); %> <% while(resultOptions.next()) { %> <%=resultOptions.getString("optionmessage") %> <% } } //connection.close(); } catch (Exception e) { e.printStackTrace(); } %> 
2
  • Good code indentation would help us read the code and more importantly it will help you debug your code Take a quick look at a coding standard for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. Commented Jun 24, 2021 at 14:37
  • You can easily solve this by using a single query with a join. It will likely perform better than your current N+1 query problem. Commented Jun 24, 2021 at 17:17

1 Answer 1

0

You need to use a separate statement for the options retrieval query. As per Statement documentation:

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a current ResultSet object of the statement if an open one exists.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.